DEV Community

Cover image for Encrypting Sensitive Information using Laravel Database Encryption Package
Nkwaten
Nkwaten

Posted on

Encrypting Sensitive Information using Laravel Database Encryption Package

Introduction

In this guide, we are going to learn how to encrypt our databases in our Laravel application to protect data. Developers sometimes consider encryption an afterthought but it is essential that encryption techniques are considered in the early stage of development especially when dealing with sensitive user data.

Requirements

Laravel: Laravel is a web application framework with expressive, elegant syntax. Supported versions > 5.x.x. The version used in this guide is Laravel 8.

Laravel Database Encryption Package: This is a package from Elgiborsolution for encrypting and decrypting model attributes for Laravel using OpenSSL. The package is simple and easy to use. All you need to to specify the fields/attributes you want to encrypt and "voila" the work is done. The package uses the encryption key in your .env.

Tutorial

  1. Install the package via composer using the command line

$ composer require elgibor-solution/laravel-database-encryption

  1. To encrypt a field of data use the EncryptedAttribute trait in the model where you want to apply the encryption. For example, if you want to encrypt the name_of_spouse, address_of_spouse and occupation_of_spouse attributes in the Family model, you do the following:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use ESolution\DBEncryption\Traits\EncryptedAttribute;

class Family extends Model
{

    use EncryptedAttribute;

    protected $encryptable = [
        'name_of_spouse','maiden_name_of_spouse','address_of_spouse'
    ];

}

Enter fullscreen mode Exit fullscreen mode

This tells the package which properties are to be encrypted.

  1. If you have an empty database and have not run migrations, you can run your database migrations and the columns are automatically encrypted.

  2. If you already have data in your database you can encrypt it with the following artisan command.

php artisan encryptable:encryptModel 'App\Models\Family'

And that's how you protect user data by working with Laravel database encryption.

*Other features *

To decrypt your database you use the following artisan command:

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

To decrypt a record in your controller you can use Encrypter method

use ESolution\DBEncryption\Encrypter;

class RecordsController extends Controller{

 public function index(){

            'name_of_spouse'=>Encrypter::decrypt($family->name_of_spouse),

}

}

Enter fullscreen mode Exit fullscreen mode

To learn more about the package read the documentation and give them a star on GitHub

https://github.com/elgiborsolution/laravel-database-encryption#laravel-database-encryption-package

Top comments (0)