How to Encrypt User Model Data in Laravel

In this post we will go over and understand, how you can encrypt the user information like name and email and store it in the database with Laravel.

Laravel provides a out-of the box authentication which can be generated using artisan make:auth command, I will demonstrate How to Encrypt User Model Data in Laravel and store it into the database on the top of Laravel Basic authentication.

Before we go ahead make sure you have following ready.

  • Laravel project setup with basic authentication enabled.
  • Project connected to the database along with tables created via migration.

Encrypt User Model Data in Laravel

Alright, encrypting and decrypting information is very easy. We will be making use of Accessors and Mutators in Laravel (Getters and Setters) to make sure whenever we store the information into model attributes we will encrypt it and whenever we are retrieving the value we will decrypt it.

Here is how the User model looks with accessors and mutators.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Crypt;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */    protected $hidden = [
        'password', 'remember_token',
    ];

    public function getNameAttribute($value) {
        return Crypt::decryptString($value);
    }

    public function getEmailAttribute($value) {
        return Crypt::decryptString($value);
    }

    public function setNameAttribute($value) {
        $this->attributes['name'] = Crypt::encryptString($value);
    }

    public function setEmailAttribute($value) {
        $this->attributes['email'] = Crypt::encryptString($value);
    }
}

 

We are making use of Laravel encryption functionality to encrypt and decrypt the data. As you can see the accessors and mutators code is straightforward, in accessors we decrypt the value using decryptString function and in mutator we encrypt the value using encryptString function.

With this code in place, whenever a new user registers for the application, his name and email will be stored in the database in encrypted format.

Something like given below

 

That’s it, If you are looking to make a search on the encrypted data you can refer

How to Search Encrypted records in Laravel

tgugnani: Web Stuff Enthusiast.