Laravel 8 - Encryption and decryption model data using Crypt class with Example

  569 views   1 week ago Laravel

In this article, i will share with you how to do encrypt and decrypt model data using Crypto class with example. when you work with banking-related web applications and if you want to get a PCI certificate for this application then data encryption is most important in this banking sector web application.

Laravel provides some helpful functionality for model data encryption and decrypt without implementing more login in your web application. and it's also a fast and most secure way to database info encrypt and decrypt.

Here, I will try to show you a very simple way to how to do model data encrypt and decrypt in laravel application.

Laravel uses the .env application key for data encrypts or decrypt. here is a simple example of how to encrypt your value and how to decrypt your data.

Encrypt

First, we will see here a simple example of how to encrypt value in laravel application.

Example - 1

public function storeSecret(Request $request, $id)
{
    $user = User::findOrFail($id);

    $user->fill([
        'secret' => encrypt($request->secret),
    ])->save();
}

Example - 2

use Illuminate\Support\Facades\Crypt;

$encrypted = Crypt::encryptString('Hello world.');

dd($encrypted);

Decrypt

First, we will see here a simple example of how to decrypt value in laravel application.

Example - 1

use Illuminate\Contracts\Encryption\DecryptException;

try {
    $decrypted = decrypt($encryptedValue);
} catch (DecryptException $e) {
    //
}

Example - 2

$decrypted = Crypt::decryptString('Your encrypted value here');

dd($decrypted);

Now, you may be understood basic things of laravel encrypt and decrypt function how it works in laravevl application. in this article, we will share with you one full example of how to work laravel encrypt and decrypt work in any real web application in a very easy way. if you have never before done laravel encrypt and decrypt in laravel application then don't worry we will here share with you all the things step by step. so, just follow the step and then you will easy to use in your any laravel application.

Step - 1 : Create Laravel8 Application

First, we need to create one laravel 8 application in our local system by running the following composer command in the terminal.

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

Step - 2 : Create Migration

Now, we need to create a migration for the transactions table. run the following command in your terminal.

php artisan make:migration create_transactions_tbl

After running this command, then open that created file which will be created in database/migrations the folder. just open it and put the following code into that migration file.

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

class Transactions extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('transactions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name_on_card');
            $table->text('card_no');
            $table->text('exp_month');
            $table->text('exp_year');
            $table->text('cvv');
            $table->timestamps();
        });
    }

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

run the above migration by

php artisan migrate

Step - 3 : Create Route Resource.

Now, we need to create the following laravel resource route in your routes/web.php. if you don't know about laravel route resource then click this link Laravel route resource and get more information about it.

use App\Http\Controllers\TransactionController;

Route::resource('transactions', TransactionController::class);

Step - 4 : Create Controller

Now, we need to create our Controller by running the following artisan command in the terminal.

php artisan make:controller TransactionController --resource

This command will generate a controller at app/Http/Controllers/TransactionController.php. The controller will contain a method for each of the available resource operations. Next, you may register a resource route that points to the controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Transaction;
use Session;

class TransactionController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->Transaction = new Transaction;

        $this->title = 'Transaction';
        $this->path = 'transactions';
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = $this->Transaction->getData();
        
        return view($this->path.'.index', compact('data'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'name_on_card' =>'required',
            'card_no' =>'required',
            'exp_month' =>'required',
            'exp_year' =>'required',
            'cvv' =>'required'
        ]);

        $inputs = $request->all();

        if($this->Transaction->storeData($inputs)) {
            Session::put('success','Your transaction store successfully.');
            return redirect()->route('transactions.index');
        } else {
            Session::put('error','Something Went Wrong. Please try again..!!');
            return redirect()->back();
        }
    }
}

Step - 5 : Create Model.

Now create app\Models\Transaction.php model and write into this model the following code. i was here to use login for model data encrypt and decrypt.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Pagination\Paginator;

class Transaction extends Model
{
    protected $table = 'transactions';
    protected $guarded = array();

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

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

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

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

    public function getCardNoAttribute($value)
    {
        try {
            return Crypt::decryptString($value);
        } catch (\Exception $e) {
            return $value;
        }
    }

    public function getexpMonthAttribute($value)
    {
        try {
            return Crypt::decryptString($value);
        } catch (\Exception $e) {
            return $value;
        }
    }

    public function getexpYearAttribute($value)
    {
        try {
            return Crypt::decryptString($value);
        } catch (\Exception $e) {
            return $value;
        }
    }

    public function getCvvAttribute($value)
    {
        try {
            return Crypt::decryptString($value);
        } catch (\Exception $e) {
            return $value;
        }
    }

    public function getData()
    {
        return static::orderBy('created_at','desc')->paginate(5);
    }

    public function storeData($input)
    {
        return static::create($input);
    }
}

Here in this app\Models\Transaction.php the model i used getter & setter method. if you want to know more about is click here

Step - 6 : Create Index Blade Files

After done controller and model then we need to create index.blade.php file in resources/views/transactions folder. in the index blade we simply listing all the transaction data. here you can see your all encrypted data listing with decrypt and readable formate.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12 text-right">
            <a href="{{ route('transactions.create') }}" class="btn btn-info pull-right">Create Transaction</a>
        </div>
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">{{ __('Users Listing') }}</div>

                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered datatable">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>Name on card</th>
                                    <th>Card No.</th>
                                    <th>Exp. Month</th>
                                    <th>Exp. Year</th>
                                    <th>CVV</th>
                                    <th width="150" class="text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @if(!empty($data) && $data->count())
                                    @foreach($data as $key=>$value)
                                        <tr>
                                            <td>{{ $value->id }}</td>
                                            <td>{{ $value->name_on_card }}</td>
                                            <td>{{ $value->card_no }}</td>
                                            <td>{{ $value->exp_month }}</td>
                                            <td>{{ $value->exp_year }}</td>
                                            <td>{{ $value->cvv }}</td>
                                            <td class="text-center">
                                                <a href="{{ route('transactions.edit', $value->id) }}" class="btn btn-success">Edit</a>
                                            </td>
                                        </tr>
                                    @endforeach
                                @else
                                    <tr>
                                       <td colspan="7">No any transaction right now found..</td> 
                                    </tr>
                                @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step - 7 : Crete Store Blade File.

After done controller and model then we need to create create.blade.php a file in resources/views/transactions folder. we can put here simply create transaction HTML form code. so, we can create transaction help of this form and it will be store in the database as a encrypted formate.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            @if($message = Session::get('error'))
            <div class="alert alert-danger alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert">×</button>
                <div class="alert-icon contrast-alert">
                    <i class="fa fa-times"></i>
                </div>
                <div class="alert-message">
                    <span><strong>Error!</strong> {{ $message }}</span>
                </div>
            </div>
            @endif
            {!! Session::forget('error') !!}
            @if($message = Session::get('success'))
            <div class="alert alert-success alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert">×</button>
                <div class="alert-icon contrast-alert">
                    <i class="fa fa-times"></i>
                </div>
                <div class="alert-message">
                    <span><strong>Success!</strong> {{ $message }}</span>
                </div>
            </div>
            @endif
            {!! Session::forget('success') !!}
        </div>        
    </div>
    <div class="row justify-content-center">
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">{{ __('Make Transaction') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('transactions.store') }}">
                        @csrf
                        <div class="form-group row">
                            <div class="col-md-12">
                                <input id="name_on_card" type="text" class="form-control @error('name_on_card') is-invalid @enderror" name="name_on_card" value="{{ old('name_on_card') }}" required autocomplete="name_on_card" placeholder="Name On Card" autofocus>
                                @error('name_on_card')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        <div class="form-group row">
                            <div class="col-md-12">
                                <input id="card_no" type="text" class="form-control @error('card_no') is-invalid @enderror" name="card_no" value="{{ old('card_no') }}" required autocomplete="card_no" placeholder="Card No." autofocus>
                                @error('card_no')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        <div class="form-group row">
                            <div class="col-md-6">
                                <input id="exp_month" type="text" class="form-control @error('exp_month') is-invalid @enderror" name="exp_month" value="{{ old('exp_month') }}" required autocomplete="exp_month" placeholder="Exp. Month (Eg. 02)" autofocus>
                                @error('exp_month')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            <div class="col-md-6">
                                <input id="exp_year" type="text" class="form-control @error('exp_year') is-invalid @enderror" name="exp_year" value="{{ old('exp_year') }}" required autocomplete="exp_year" placeholder="Exp. Year (Eg. 2020)" autofocus>
                                @error('exp_year')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        <div class="form-group row">
                            <div class="col-md-12">
                                <input id="cvv" type="password" class="form-control @error('cvv') is-invalid @enderror" name="cvv" required autocomplete="current-password" placeholder="CVV">
                                @error('cvv')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-primary btn-block">
                                    {{ __('PAY NOW') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

i hope you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles