Laravel 8 Automatic Database Encryption Decryption

Laravel 8 Automatic Database Encryption Decryption

Hello friends, Today we will show Laravel 8 Automatic Database Encryption Decryption with Eloquent. We will learn how to automatic data encryption with eloquent in laravel 8 application. I will show how to encryption and decryption work in a database by the way laravel provide package elgibor-solution/laravel-database-encryption.

Here we will show how to automatic data encryption with eloquent in laravel 8,  database encryption and decryption using elgibor-solution package using laravel 8,  database encryption and decryption using elgibor-solution package.

In this example we will give you full example of automatic data encryption with eloquent in laravel 8 using elgibor-solution package as following so follow my all steps.

Read also : CRUD with Image Upload in Laravel 8 Example

Laravel 8 Automatic Database Encryption Decryption

Step 1 : Install Laravel 8

First, we required to get fresh laravel 8 version application So let’s open terminal and run follow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel encryption

Step 2 : Database Configuration

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=laravel_8

DB_USERNAME=root

DB_PASSWORD=

Step 3 : Install elgibor-solution package

We will install elgibor-solution package Via Composer command line:

composer require elgibor-solution/laravel-database-encryption

After successfully install package, open config/app.php file and add service provider.

'providers' => [

    ...

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

],

Step 4 : Usage In Model

Now will use the EncryptedAttribute trait in any Eloquent model that you wish to apply encryption to and define a protected $encrypted array containing a list of the attributes to encrypt.

<?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 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',
    ];

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

Step 5 : Create Route

<?php

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

Route::resource('users', UserController::class);

Step 6 :Create Controller

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(Request $request)
    {
        $users = User::all();
        return view('user.index',compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('user.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
        $validated = $request->validate([
            'name' => 'required|unique:users',
            'email' => 'required',
            'password' => 'required'
         ]);
        
        User::create($input);
        return redirect()->route('users.index');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $users = User::find($id);
        return view('user.edit',compact('users'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $input = $request->all();
        $request->validate([
            'name' => 'required',
        ]);
        $user = User::find($id);
        $user->update($input);
        return redirect()->route('users.index');
    }
}

Step 6 : Create a blade view

resources/views/user/index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>web-tuts.com</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />
    <style type="text/css">
        table.dataTable.no-footer {
            border-bottom: 2px solid #f2f2f2;
        }
        .blog-img {
            width: 200px;
            height: 100px;
        }
    </style>
</head>
<body>
<section class="content mt-5">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-9">
                                 <h4>Laravel 8 Automatic Data Encryption with Eloquent - <span class="text-primary">web-tuts.com</span></h4>
                            </div>
                            <div class="col-md-3 text-right">
                                <a href="{{ route('users.create')}}" class="btn btn-success"><i class="fa fa-plus"></i></a>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered data-table">
                            <thead>
                                <tr>
                                    <th width="7%">#</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th width="12%">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            @if(!empty($users) && $users->count())
                                @foreach($users as $key => $value)
                                <tr>
                                    <td>{{ ++$key }}</td>
                                    <td>{{ $value->name }}</td>
                                    <td>{{ $value->email }}</td>
                                    <td>
                                        <a href="{{ route('users.edit',$value->id) }}" class="btn btn-primary"><i class="fa fa-pencil"></i></a>
                                    </td>
                                </tr>
                                @endforeach
                            @else
                            <tr>
                                <td colspan="4" class="text-center">There are no data found</td>
                            </tr>
                            @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
</body>
</html>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

resources/views/user/create.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>web-tuts.com</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="content-header mt-5">
        <div class="container">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h4 class="m-0">Create User</h4>
                </div>
            </div>
        </div>
    </div>
    <section class="content">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body">
                            @if(count($errors) > 0)
                            <div class="alert alert-danger alert-dismissible">
                                <button type="button" class="close" data-dismiss="alert">×</button>
                                @foreach($errors->all() as $error)
                                    <span>{{ $error }}</span><br>
                                @endforeach
                            </div>
                            @endif
                            <div class="row">
                                <div class="col-md-12">
                                    <form action="{{ route('users.store')}}" method="POST" autocomplete="off">
                                        @csrf
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label for="inputname3">Name:</label>
                                                <div class="form-group">
                                                    <input type="text" name="name" placeholder="Enter Name" class="form-control">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="inputname3">Email:</label>
                                                <div class="form-group">
                                                    <input type="email" name="email" placeholder="Enter Email" class="form-control">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                               <label for="inputname3">Password:</label>
                                                <div class="form-group">
                                                    <input type="password" name="password" placeholder="Enter Password" class="form-control">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="box-footer text-center">
                                            <button type="submit" class="btn btn-success btn-flat"><i class="fa fa-floppy-o"></i> Save</button>
                                            <a href="{{ route('users.index') }}" class="btn btn-danger btn-flat"><i class="fa fa-times"></i> Cancel</a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>    
</body>
</html>

resources/views/user/edit.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>web-tuts.com</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha512-5A8nwdMOWrSz20fDsjczgUidUBR8liPYU+WymTZP1lmY9G6Oc7HlZv156XqnsgNUzTyMefFTcsFH/tnJE/+xBg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="content-header mt-5">
        <div class="container">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h4 class="m-0">Edit User</h4>
                </div>
            </div>
        </div>
    </div>
    <section class="content">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body">
                            @if(count($errors) > 0)
                                <div class="alert alert-danger alert-dismissible">
                                    <button type="button" class="close" data-dismiss="alert">×</button>
                                    @foreach($errors->all() as $error)
                                        <span>{{ $error }}</span><br>
                                    @endforeach
                                </div>
                            @endif
                            <div class="row">
                                <div class="col-md-12">
                                    <form action="{{ route('"users.update",$users->id')}}" method="PATCH" autocomplete="off">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label for="inputname3">Name:</label>
                                                <div class="form-group">
                                                    <input type="text" name="name" placeholder="Enter Name" class="form-control">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="inputname3">Email:</label>
                                                <div class="form-group">
                                                    <input type="email" name="email" placeholder="Enter Email" class="form-control">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                               <label for="inputname3">Password:</label>
                                                <div class="form-group">
                                                    <input type="password" name="password" placeholder="Enter Password" class="form-control">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="box-footer text-center">
                                            <button type="submit" class="btn btn-success btn-flat"><i class="fa fa-floppy-o"></i> Update</button>
                                            <a href="{{ route('users.index') }}" class="btn btn-danger btn-flat"><i class="fa fa-times"></i> Cancel</a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</body>
</html>

Step 7 : Encrypt your current data

If you have current data in your database you can encrypt it with the command follow.

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

If you have current data in your database you can decrypt it with the command follow.

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

Note: You must implement first the encryptable trait and set $encryptable attributes

Read Also :  Laravel Blade If Multiple Conditions Example

Now, we will use the php artisan serve command.

php artisan serve

Now we are ready to run our example so run follow command to quick run.

http://localhost:8000/users

I hope you understand of Automatic Database Encryption Decryption in Laravel 8 and it can help you…