How to Encrypt Database Fields in Laravel 8

How to Encrypt Database Fields in Laravel 8?

In this tutorial, I will give you an example of “How to Encrypt Database Fields in Laravel 8”, So you can easily apply it with your laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

encrypt database field in laravel

encrypt a value in laravel

Need Of Encrypt any data field in laravel

Sometimes we have some sensitive data like (passport number, product SKU, category SKU code, debit card, credit card security number) and you don’t want to people access it even if someone hacked your database and get the database out. The data will be encrypted and not readable.

Encryption using Laravel Encrypted Casting

Before in laravel, we used to Db Encrypter Package for encryption, in this package we define which field we want to be encrypted, and when we save the database. It saves as encrypted data in the table and when we get the data the data field will be in decrypted form.

In this example, we will use Laravel Encrypted Casting.

Encrypted Casting

The encrypted cast encrypts a model’s attribute value using Laravel’s built-in encryption features. In addition, the encrypted: array, encrypted: collection, and encrypted: object casts work like their unencrypted counterparts.

Generating Migration :

php artisan make:migration create_categories_table

Migration Structure :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('sku');
            $table->longText('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

We will encrypt the SKU field, The final length of the encrypted text is not predictable and is longer than its plain text counterpart, make sure the associated database column will be of TEXT type or larger.

Run Migration :

php artisan migrate

Create a Model :

php artisan make:model Category

App\Models\Category.php :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;
    protected $table="categories";

    protected $hidden = [
        'sku',
    ];

    protected $casts = [
        'sku' => 'encrypted',
    ];
}

We want to encrypt the SKU field so we put it on protected $caste like: ‘sku’ => ‘encrypted’,

Create a Controller :

php artisan make:controller CategoryController

Define Routes :

routes\web.php :

<?php

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

Route::get('/add-category', [CategoryController::class, 'addcategory'])->name('add.cat');
Route::get('/category-list', [CategoryController::class, 'listcategory'])->name('cat.list'); 
Route::post('/category-store', [CategoryController::class, 'storecategory'])->name('cat.store');

app\Http\Controllers\CategoryController :

<?php

namespace App\Http\Controllers;

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

class CategoryController extends Controller
{
    public function addcategory()
    {
        return view('category.add');
    }

    public function listcategory()
    {
        $category = Category::get();
        return view('category.list',compact('category'));
    }

    public function storecategory(Request $request)
    {
        $cat = new Category();
        $cat->name = $request->cat_name;
        $cat->sku = $request->sku;
        $cat->description = $request->cat_description;
        $cat->save();
        return redirect()->route('cat.list')->with('flash_msg_success','Category added Successfully !');
    }
}

resources\views\category\add.blade.php :

encryption in laravel
<div class="container">
         <div class="row justify-content-center">
            <div class="col-lg-6">
               <div class="main">
                  <h3><a>Encrypt Database Fields in Laravel</a></h3>
                  <form role="form" action="{{route('cat.store')}}" method="post">
                     @csrf
                     <div class="form-group">
                        <label for="name">Category Name <span class="text-danger">*</span></label>
                        <input type="text" name="cat_name" class="form-control">
                     </div>
                     <div class="form-group">
                        <label for="sku">Category SKU <span class="text-danger">*</span></label>
                        <input type="text" name="sku" class="form-control">
                     </div>
                     <div class="form-group">
                        <label for="description  not ">Category Description <span class="text-danger">*</span></label>
                        <input type="text" name="cat_description" class="form-control">
                     </div>
                     <div class="form-group">
                     <button type="submit" class="btn btn btn-secondary">
                      save
                     </button>
                  </form>
               </div>
            </div>
         </div>
      </div>

resources\views\category\list.blade.php :

decrypt value in laravel using encrypt casting
 <div class="container">
         <h3>Encrypt Database Fields in Laravel</h3>
         <br>
         <table class="table">
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>Category name</th>
                  <th>Category SKU</th>
                  <th>Category Description</th>
               </tr>
            </thead>
            <tbody>
               @foreach($category as $key => $data)
               <tr>
                  <td>{{ $key+1 }}</td>
                  <td>{{ $data->name }}</td>
                  <td>{{ $data->sku }}</td>
                  <td>{{ $data->description }}</td>
               </tr>
            </tbody>
            @endforeach
         </table>
      </div>

Note: Please don’t use the decryption for basic operations, you just store it and forget about it unless you need it.

encrypt value in laravel using encrypt casting

Encrypted Casting is very powerful, even someone steals your database, he would not able to decrypt the database unless the APP KEY is in the .env file,

APP_KEY is a key for making encryption and decryption.

In this article, we learned “How to Encrypt Database Fields in Laravel 8”, I hope this article will help you with your Laravel application Project.

Read Also: Prevent Back Button After Logout in Laravel.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com