How to Encrypt and Decrypt Database Fields in Laravel

Sovary November 10, 2022 589
5 minutes read

Today we will share with you how to encrypt model data field in Laravel with the eloquent. We will see example automatic encrypt and decrypt fields which will write in database so this will be helpful for security as well. The package which will help complete today project is elgibor-solution/laravel-database-encryption.

This package is provide automatic data encryption with eloquent in Laravel and support decrypt when load data display to front-end, so that user can read normally. Most of the packages do not support search at the encrypted information, but this package will provide fully search data with encryption.

Let's look at below example step by step of automatic data encryption with eloquent in Laravel using elgibor-solution package which we are going to do it from scratch.

Encrypt and Decrypt Data Model Fields in Laravel

  • Step 1 - Install Laravel Project
  • Step 2 - Setting Database Connection
  • Step 3 - Install Package
  • Step 4 - Setup Encrypt Model
  • Step 5 - Add Route
  • Step 6 - Create Controller
  • Step 7 - Display in Blade
  • Step 8 - Encrypt Decrypt Current Data
  • Step 9 - Run Laravel Server

Step 1 - Install Laravel Project

First step you have to download Laravel project, so you have to connect to internet and installed via composer. You may read how to configure database connection and installation in the article or just follow this article.

Now let's download Laravel with below command

composer create-project laravel/laravel blog

The last parameter (blog) which is your project name, so you can put whatever you want.

Step 2 - Setting Database Connection

Now this step we are going to setting the database connection which we will write and read data from database. Let's open the .env file which is located in root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Step 3 - Install Package

This step we will install package to help encrypt and decrypt data in Model class. Let's open terminal to run command below

composer require elgibor-solution/laravel-database-encryption

After installation package we have to updated array in service provider.

Open file config -> app.php

'providers' => [

    ...

	\ESolution\DBEncryption\Providers\DBEncryptionServiceProvider::class,
],

Step 4 - Setup Encrypt Model

This step is important part to enable encryption. We will use EncryptedAttribute trait in Eloquent model and define an array  $encryptable which contain list of the fields to encrypt.

Example below we will use existing User model class

<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use ESolution\DBEncryption\Traits\EncryptedAttribute;
class User extends Authenticatable
{
    use HasFactory, Notifiable, EncryptedAttribute;

    /**
     * The attributes that should be encrypted on save.
     *
     * @var array
     */
    protected $encryptable = [
        'name','email','password'
    ];

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

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

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

}

Step 5 - Add Route

We will access a specific URL to display decrypt data from database, so we will add a link in route file.

Open file routes -> Web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/users', UserController::class);

Step 6 - Create Controller

We will create controller file to implement and retrieved data from database, and there is existing User controller file, so we are going to implement a method to display database in browser

Open file app -> Http -> Controllers -> UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::all();
        dd($users);
    }
}

Step 7 - Display in Blade

We will create a blade file in resource directory. We will use that blade file to display decryption data.

Create file resources -> views -> index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Encrypt Decrypt Data Laravel 9 - CamboTutorial.com</title>
</head>
<body>
<div class="container">
    <div class="panel panel-primary">
      <div class="panel-heading">
        <h2>Encrypt Decrypt Data Laravel 9 - CamboTutorial.com</h2>
      </div>
      <div class="panel-body">
        @foreach($users as $user)
        <p>{{ $user->email }}</p>
        @endforeach
      </div>
    </div>
</div>
</body>
</html>

Step 8 - Encrypt Decrypt Current Data

Now, let's me tell you how to encrypt data if you already have existing data in database. What you have to do is run the below command.

NOTE: before you run below command, make sure you have implemented Encryptable trait and set $encryptable field at first place.
php artisan encryptable:encryptModel 'App\Models\User'

You may place the path were you model located in last parameter of command.

Anyway if you want to decrypt data which exist in your database, the command should run as below

php artisan encryptable:decryptModel 'App\Models\User'

You can see we don't have to do encrypt or decrypt much because everything has been done in model class, just little implemented encryption then the package does all.

Step 9 - Run Laravel Server

Now it's time to run app server for testing, we will show you either front-end or database table. Let's run following command to run the server

php artisan serve

Hope this article help you to encrypt and decrypt data in Model class. Have a nice day!!

You may also like...

 

Laravel  PHP  Laravel 9 
Author

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him