How to Search Encrypted records in Laravel

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 ! 

3 comments On How to Search Encrypted records in Laravel

  • I understood the logic, but in case of a bulky record set, this will take enormous time. Is there any possible way to achieve the same target.

  • Hi, why don’t you do the opposite.
    Hash the search value and perform a common sql search.
    Thanks!

Leave a reply:

Your email address will not be published.

Site Footer