How to Encrypt and Decrypt Database Fields in Laravel 10

In the ever-evolving landscape of web development, data security remains paramount to me. As applications become more complex and handle increasingly sensitive information, safeguarding that data has become my top priority.

Laravel, a popular PHP web application framework known for its elegant syntax and robust features, offers a powerful solution for securing my database fields. In this step-by-step guide, I will explore how to encrypt and decrypt database fields in Laravel 10, ensuring that my sensitive data is shielded from prying eyes and unauthorized access.

By employing encryption, I can fortify my application against potential breaches, data leaks, and privacy violations. Laravel's seamless integration of encryption features simplifies the process, allowing me to focus on building secure and reliable applications.

Whether I am dealing with user credentials, financial data, or any other confidential information, this guide will walk me through the essential steps to implement encryption and decryption, keeping my data locked away from the grasp of malevolent actors.

So, let's see how to encrypt and decrypt database fields in laravel 10, laravel encrypt and decrypt database fields, how to encrypt database fields in laravel 10, laravel encrypted cast.

Step 1: Set Up Your Laravel Project

Before you can start encrypting and decrypting database fields, you need to have a Laravel project up and running. You can create a new Laravel project by running the following command.

composer create-project laravel/laravel my-laravel-project

 

Step 2: Configure Your Database

Open the .env file in your Laravel project's root directory and configure your database connection settings. You can use MySQL, PostgreSQL, SQLite, or any other supported database system.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

 

Step 3: Create Products Table

Generate a migration for your model and run the migration to create the database table.

php artisan make:migration create_products_table

Migration:

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

Edit the migration file to define the table structure and then run the migration.

php artisan migrate

 

 

Step 4: Define Encryption and Decryption Logic in the Model

Open the Product.php model you just created and define the fields you want to encrypt. You can use the encrypt and decrypt methods provided by Laravel's 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'
    ];
}

 

Step 5: Create Controller

Now, we will create a 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.');
    }
}

 

Step 6: Add Route

Now, we will add 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');

 
Step 7: Create View File

Then, we will create a blade file for display data.

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 - Techsolutionstuff</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 - Techsolutionstuff</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>

 
Laravel 8: Run Laravel 10 Application

Run the laravel application using the following command.

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS