How to Encrypt and Decrypt Database Fields in Laravel 10

  Nov 2023
  ITSolutionsGuides
  Category: Laravel
How to Encrypt and Decrypt Database Fields in Laravel 10

Hi Developers,

Explore the cutting-edge world of Laravel 10 with IT Solutions Guides! Our latest tutorial dives into the realm of database security, focusing on encrypting and decrypting database fields. Learn the advanced techniques of Laravel 10, discovering how to fortify your application's data integrity. Uncover the intricacies of encrypting database fields, implementing Laravel's encrypted cast feature to ensure top-notch security. We guide you through the step-by-step process of safeguarding sensitive information within your Laravel 10 project, empowering you to navigate the evolving landscape of web development. Elevate your skills with IT Solutions Guides, your trusted source for staying ahead in the tech industry.

Lets see How to Encrypt and Decrypt Database Fields in Laravel
Learn how to enhance security in Laravel by encrypting and decrypting database fields. Safeguard sensitive information effectively with our step-by-step tutorial.

Lets Create the Migration

Lets install the new laravel project and create the products table by using the following artisan command,

php artisan make:migration create_products_table

after creating the migration lets declare the required columns in the migration table.

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

Lets Write Encryption and Decryption Logic in the Model

Lets run the migration file using the following artisan command

php artisan migrate

Then in the Product.php model lets declare the database fields that need to be encrypted , By using the encrypt and decrypt methods from the Laravel Eloquent ORM.

<?php

namespace App\Models;

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

class Product extends Model
{

    use HasFactory;  

    /**
     * Write code on Method
     *
     * @return response()
     */

    protected $fillable = [
        'name', 'code', 'detail'
    ];
  

    /**
     * Write code on Method
     *
     * @return response()
     */

    protected $hidden = [
        'name', 'code', 'detail'
    ];
  

    /**
     * Write code on Method
     *
     * @return response()
     */

    protected $casts = [
        'name' => 'encrypted',
        'code' => 'encrypted',
        'detail' => 'encrypted'
    ];
}

Lets Create the Controller

Lets create the controller using the following artisan command ,

php artisan make:controller ProductController

app/Http/Controllers/ProductController.php.

<?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
{

    /**
     * Display a listing of the resource.
     *
     * @return response()
     */

    public function index(): View
    {
        $products = Product::get();      
        return view('products',compact('products'));
    }

  

    /**
     * Store a newly created resource in storage.
     */

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

Lets Create the Route

Lets add the required routes in the web.php file.

routes/web.php

<?php

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

  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Lets Create Blade Files

resources/views/products.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>How to Encrypt and Decrypt Database Fields in Laravel 10 </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">
                <h2>How to Encrypt and Decrypt Database Fields in Laravel 10</h2>
            </div>
        </div>
    </div>
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif  

    <form method="post" action="{{ route('products.store') }}" enctype="multipart/form-data">
        @csrf
        <div class="form-group">
            <label>Name</label>
            <input type="text" name="name" class="form-control" />
        </div>

        <div class="form-group">
            <label>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>No</th>
            <th>Name</th>
            <th>Code</th>
            <th>Details</th>
        </tr>

        @foreach ($products as $k => $product)
        <tr>
            <td>{{ ++$k }}</td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->code }}</td>
            <td>{{ $product->detail }}</td>
        </tr>
        @endforeach
    </table>          
</div>
</body>
</html>

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides