Laravel 10 How To Encrypt Decrypt Values in Database

Reading Time: 7 minutes
404 Views

Data security is critical in web application development, and encrypting sensitive information is a critical component of protecting your data. Laravel, a powerful PHP framework, includes strong encryption and decryption techniques that can be smoothly incorporated into database operations.

We will walk you through the process of encrypting and decrypting values in a database using Laravel 10, providing you with the knowledge and tools you need to improve data security in your applications.

This tutorial will go over the strategies and best practises for safeguarding data in your Laravel project. We’ll go through how to incorporate encryption into your database schema, as well as data insertion, retrieval, and decryption.

Read More: Laravel 10 How To Capture Website Screenshot Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

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

Setup Model & Migration

Open project into terminal and run this command,

php artisan make:model Product -m

It will create two files,

  • Model – Product.php inside /app/Models folder
  • Migration file – xxx_create_products_table.php inside /database/migrations folder.

Open migration file and write this complete code into it,

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->text('name');
            $table->text('detail');
            $table->text('code');
            $table->timestamps();
        });
    }

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

Run Migration

Next, you need to migrate migration files,

php artisan migrate

This command will create tables inside database. It also create products table in database.

Read More: Laravel 10 How To Create Multi Language Website Tutorial

Next,

Open model file and write this complete code into it,

<?php

namespace App\Models; 

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

class Product extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name', 'code', 'detail'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'name', 'code', 'detail'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'name' => 'encrypted',
        'code' => 'encrypted',
        'detail' => 'encrypted'
    ];
}

Setup Product Controller

Next, you need to create a controller class,

php artisan make:controller ProductController

It will create a file ProductController.php inside /app/Http/Controllers folder.

Open file and write this complete code into it,

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use App\Models\Product;
  
class ProductController extends Controller
{
    public function index(): View
    {
        $products = Product::get();
      
        return view('products',compact('products'));
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => 'required',
            'code' => 'required',
            'detail' => 'required'
        ]);
    
        $input = $request->all();
       
        Product::create($input);
       
        return redirect()->route('products.index')
                        ->with('success','Product added successfully.');
    }
}

Create Blade Template File

Go to /resources/views folder and create a file with name products.blade.php

Read More: Laravel 10 Language Translation Methods Tutorial

Open file and write this complete code into it,

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel 10 How To Encrypt Decrypt Values in Database</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css">
</head>

<body>

    <div class="container mt-5">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h3>Laravel 10 How To Encrypt Decrypt Values in Database</h3>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-8">

                @if ($message = Session::get('success'))
                <div class="alert alert-success">
                    <p>{{ $message }}</p>
                </div>
                @endif

                <form method="post" action="{{ route('products.store') }}">
                    @csrf
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" name="name" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Product Code</label>
                        <input type="text" name="code" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Details</label>
                        <textarea id="summernote" class="form-control" name="detail"></textarea>
                    </div>
                    <div class="form-group mt-3 mb-3">
                        <button type="submit" class="btn btn-success btn-block">Submit</button>
                    </div>
                </form>

                <table class="table table-bordered">
                    <tr>
                        <th>#ID</th>
                        <th>#Name</th>
                        <th>#ProductCode</th>
                        <th>#Detail</th>
                    </tr>
                    @foreach ($products as $i => $product)
                    <tr>
                        <td>{{ ++$i }}</td>
                        <td>{{ $product->name }}</td>
                        <td>{{ $product->code }}</td>
                        <td>{{ $product->detail }}</td>
                    </tr>
                    @endforeach
                </table>
            </div>
        </div>

    </div>

</body>

</html>

Add Route

Open web.php file from /routes folder. Add these routes into it.

//...

use App\Http\Controllers\ProductController;

//...

Route::get('products', [ProductController::class, 'index'])->name('products.index');
Route::post('products', [ProductController::class, 'store'])->name('products.store');

//...

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/products

Add Product and List Product View

Once you save product, It will automatic lists all products in plain text which is human readable texts (Values are Decrypted)

Back to database,

Database View

Saved values are encrypted in table products (Values are Encrypted).

That’s it.

We hope this article helped you to learn about Laravel 10 How To Encrypt Decrypt Values in Database Example Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.