There are times when you are supposed to code a functionality that will require you to Search Encrypted records in Laravel.
I have been involved in a Medical project where it is required to encrypt the user’s first name and last name in the database. How do we perform search on the data that is encrypted.
As a caution don’t encrypt the data that needs to searched unless there is a sure requirement to do so. Because searching the encrypted data slows down the search performance.
Alright let’s see you can do it.
Let’s say we have a field SSN on user’s table that you believe needs to be stored in encrypted format.
You need to modify your setters and getters in User’s class to do the encryption and decryption job for you.
<?php namespace App; use Illuminate\Support\Facades\Crypt; class User extends Model{ public function setSSNAttribute($value) { $this->attributes['ssn'] = Crypt::encryptString($value); } public function getSSNAttribute($value) { return Crypt::decryptString($value); } }
Here is how you can write the search functionality
public function searchSSN($searchValue){ $items = User::all()->filter(function($record) use($searchValue) { if(($record->SSN) == $searchValue) { return $record; } }); }
As you can see this approach requires to get all the data and then perform the search on the results using Laravel collection’s filter function.
That’s it !