Laravel: How to Encrypt Decrypt Database Fields

You will learn how Laravel encrypts database fields in this lesson. This article covers how to encrypt and decode database fields in Laravel in depth. It’s an easy example of how to use Laravel to encrypt database fields. In the laravel example, you will learn how to encrypt database fields.

In this example, we’ll create a “products” table with fields for the name, the information, and the code. Our goal is to safely store encrypted data in these fields and then decrypt it before displaying it on a webpage. We’ll use Laravel model “casts” to automatically handle the encryption and decryption of field data to speed up this procedure. Let’s look at a simple illustration to show this.

DB Preview:

laravel

Display Preview:

laravel

Step 1: Install Laravel

Using the bellow command, we must first create a new Laravel version application. Run the following command after opening your terminal or command prompt:

composer create-project laravel/laravel my-app

Step 2: Create Products Table

Here, we’ll make a model for the “products” table in addition to creating a database migration for it.

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

Step 3: Create Product Model

To define encrypted casting for the name, detail, and code fields, we will construct the Product.php file for the model. Let’s change the code now.

app/Models/Product.php

<?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 4: Create Controller

In this phase, we’ll develop a ProductController that has the index() and store() methods for retrieving and storing records. So let’s use the command below to construct a controller.

php artisan make:controller ProductController

Update the controller file’s code right away.

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 5: Add Route

Open the routes/web.php file and make any necessary updates.

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 6: Create View File

Let’s construct products.blade.php in the final phase to display products and add the following code:

resources/views/products.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel Encrypt Database Fields Example - ItSolutionStuff.com</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>Udecode Database Encrypt Decrypt/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>

Run Laravel App:

After completing all necessary steps, you must now execute the command shown below and press Enter to launch the Laravel application:

php artisan serve

Now, Enter the provided URL into your web browser to view the app’s output.

http://localhost:8000/products

We are now prepared to execute this example and verify it.

10 thoughts on “Laravel: How to Encrypt Decrypt Database Fields

  1. My programmer is trying to convince me to move to .net from PHP.

    I have always disliked the idea because of the expenses. But he’s tryiong none the less.

    I’ve been using WordPress on a variety of websites for about a year
    and am nervous about switching to another platform. I have heard fantastic things about
    blogengine.net. Is there a way I can import all my wordpress content into it?
    Any help would be really appreciated!

  2. Spot on with this write-up, I really feel this web site needs far
    more attention. I’ll probably be returning to read through more, thanks for
    the advice!

  3. That is a very good tip especially to those fresh to the blogosphere.
    Simple but very precise information… Thank you for sharing this one.
    A must read post!

  4. I don’t know if it’s just me or if perhaps everyone else
    experiencing problems with your blog. It looks like some of the written text within your posts are running off
    the screen. Can someone else please provide feedback and let me know if
    this is happening to them too? This may be a problem with my
    web browser because I’ve had this happen previously. Kudos

  5. Good day! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve worked
    hard on. Any suggestions?

  6. Heya this is kinda of off topic but I was wanting to know if blogs use WYSIWYG
    editors or if you have to manually code with HTML. I’m starting a
    blog soon but have no coding skills so I wanted to get advice from someone with experience.

    Any help would be enormously appreciated!

Leave a Reply

Your email address will not be published. Required fields are marked *