Laravel6 - Encryption and decryption model data using Crypt class

We will share with you how to encrypt and decrypt laravel model data help of crypt class in laravel application. we all know that laravel is the best and secure framework right now for develop any web application. so, laravel also provide default it's own encrypt and decrypt class for data security.

You can be done database data encrypt or decrypt the help of Laravel Encryption. laravel encryption provides us many encrypt or decrypt functions that help us in data encrypt and data decrypt.

If you work with a bank system and another large web application then data security is one of the major important parts of that web application. because many times hackers hack your database and try to use your application data to miss use. but you can prevent it help of laravel encrypt and decrypt helper function and you can make your database and your data safe. so, no one any easy to ready your database data if they have your data because laravel encryption class makes your data one way encrypt and it is very hard to decode or decrypt. almost impossible.

Laravel's encrypter uses OpenSSL to provide AES-256 and AES-128 encryption. You are strongly encouraged to use Laravel's built-in encryption facilities and not attempt to roll your own "home grown" encryption algorithms. All of Laravel's encrypted values are signed using a message authentication code (MAC) so that their underlying value can not be modified once encrypted.

Laravel is use .env application key for a data encrypt 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 applications.

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 a 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 laravel 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 were 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 laravel application.

Preview

Database Encrypt Data Preview

Step - 1 Create Laravel Application.

First, we need to create one fresh laravel application help of composer command. just run the following command in your terminal and create one laravel application.

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

Step - 2 Configure Database Setting.

Now, into the second step we should configure database settings in .env a file just open your .env file and make the following changes. set your database name, username, and password.

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

Step - 3 Create Migration

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

php artisan make:migration create_transactions_tbl

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

<?php

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');
    }
}

and then run php artisan migrate commands in your terminal. then your transactions table will be created into your database, which you set into in your project .env file.

Step - 4 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 resorce then click this link Laravel route resource and get more information about it.

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

Step - 5 Create Controller.

Now, we need to create TransactionController.php file in app\Http\Controllers folder. just run the following command in your terminal and create your controller.

php artisan make:controller TransactionController --resource

Just, open your TransactionController.php file and write the following code into this controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\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 - 6 Create Model.

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

<?php

namespace App;

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\Transaction.php model, I was use getter & setter method. if you want to know more about is click here.

Step - 7 Create Index Blade Files

After done controller and model then we need to create index.blade.php a file in resources/views/transactions folder. in 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 - 8 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 stored 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

Conclusion

As you can see, database data encrypt and decrypt is very easy to use in laravel application help of Crypt class nad some laravel helper functions.

We hope these tutorials help everyone. if you have any issues or questions regarding data encryption and decryption in laravel application so please comment below. Thanks.