laravel-encrypt-and-decrypt

200OK Solutions Blog | Insights & Tutorials

A Guide to Custom Encryption Integration in Laravel Project 

Share this post on:

Introduction: 

In the ever-evolving landscape of web development, security remains a paramount concern. Laravel, a popular PHP framework, provides robust tools for implementing encryption within its models. This blog post aims to explore the complexity of encryption in Laravel models, shedding light on best practices and practical implementation tips. 

Steps: 

  1. Create a Laravel project named “laravel-encryption”

You can create a Laravel project with below composer command below: 

composer create-project laravel/ laravel-encryption –prefer-dist 

  1. Create a BaseModel.php in “app/Models” with following content: 
<?php 
namespace App\Models; 
use Illuminate\Foundation\Auth\User as Authenticatable; 
use Illuminate\Database\Eloquent\Factories\HasFactory; 
use Illuminate\Database\Eloquent\Model; 

class BaseModel extends Authenticatable 
{ 
    use HasFactory; 
    public function setAttribute($key, $value) 
    { 
        $encrypt_method = "XXX-XXX-XXX"; 
        $encrypt_key = hash('sha256', 'ABC_TEST_STRING_KEY'); 
        $encrypt_iv = substr(hash('sha256', 'ABC_TEST_STRING'), 0, 16); 
        if (in_array($key, $this->encrypt)) { 
            $value = base64_encode(openssl_encrypt($value, $encrypt_method, $encrypt_key, 0, $encrypt_iv)); 
        } 
        return parent::setAttribute($key, $value); 
    } 


    public function getAttribute($key) 
    { 
        $encrypt_method = "XXX-XXX-XXX"; 
        $encrypt_key = hash('sha256', 'ABC_TEST_STRING_KEY'); 
        $encrypt_iv = substr(hash('sha256', 'ABC_TEST_STRING'), 0, 16); 
        if (in_array($key, $this->encrypt)) { 
            return openssl_decrypt(base64_decode($this->attributes[$key]), $encrypt_method, $encrypt_key, 0, $encrypt_iv); 
        } 
        return parent::getAttribute($key); 
    } 

In the above code snippet, you need to keep your own encryption method in place of XXX-XXX-XXX. 

Also, we need 2 strings named “key” and “secret” and replace the string “ABC_TEST_STRING_KEY” with your actual key and “ABC_TEST_STRING” with your secret. This will allow you to encrypt and decrypt your all column data with these strings. So please keep this string in a safe place (.env file). 

  1. Extend app/Models/User.php with BaseModel:
<?php 
namespace App\Models; 

use App\Http\Middleware\Authenticate; 
use Illuminate\Contracts\Auth\MustVerifyEmail; 
use Illuminate\Database\Eloquent\Factories\HasFactory; 
use Illuminate\Database\Eloquent\Model; 
use Illuminate\Foundation\Auth\User as Authenticatable; 
use Illuminate\Notifications\Notifiable; 
use Illuminate\Support\Facades\Crypt; 
use Laravel\Sanctum\HasApiTokens; 

class User extends BaseModel 
{ 
    use HasApiTokens, HasFactory, Notifiable; 
    /** 
     * The attributes that are mass assignable. 
     * 
     * @var array<int, string> 
     */ 
    protected $fillable = [ 
        'id', 
        'name', 
        'username', 
        'mobile_number', 
        'email', 
        'password', 
        'profile_photo', 
    ]; 

    protected $hidden = [ 
        'password', 
    ]; 

 
    protected $encrypt = [ 
        'name', 
        'username', 
        'mobile_number', 
        'email', 
    ]; 

As mentioned in the above code snippet, we have extended BaseModel over the User model. So whenever we query the User table, we will get all decrypted values and whenever we create any new user all columns will have encrypted values in column data. 

Conclusion: 

Laravel offers powerful tools for implementing encryption within models, ensuring the security of sensitive data. By understanding the nuances of Laravel’s encryption features and adopting best practices, developers can fortify their applications against potential security threats. This comprehensive guide has aimed to equip developers with the knowledge needed to implement encryption seamlessly within Laravel models. 

BlogAdmin

Digital Transformation Counsultant (Public Sector)

25+ years experience
UK public sector & enterprise specialist
Board-level commercial leadership
Technology & consultancy expertise

Core Technologies

Business Development 95%
Digital Transformation 92%
Public Sector Solutions 90%
Cloud & AWS Partnerships 85%
  • Public Sector: Government & enterprise solution engagement
  • Commercial: Consultative business development, stakeholder management
  • Technology: Digital services, cloud-led transformation solutions
  • Leadership: Board-level advisory, operational efficiency & innovation
  • Backend: Business transformation strategy, programme delivery, solution consulting
  • Public Sector
  • Enterprise Technology
  • Consulting & Advisory
  • Programme Delivery
  • Cloud & Digital Services
  • Solving complex business challanges through technology-led innovaion
  • Combining consultancy, and delivery expertise
  • Building long-term partnershipis across enterprise & government sectors
  • Driving transformation with practical, outcome-focused solutions
  • Aligning technology investments with operational and commercial goals

BlogAdmin is an experienced digital transformation leader (public sector) with a strong track record of helping organizations solve complex operational and technology challanges through innovative commercial and technical solutions.

With extensive experience spanning consultancy, programme delivery, cloud partnerships, and strategic business dvelopment, he has worked across multiple sectors including public sector, enterprise technology, and digital services.

He brings a rare combinatioin of board-level commercial leadership and hands-on delivery understanding, enabling him to bridge the gap between business objectives and technology execution.

BlogAdmin is paricularly experienced in consultative selling, AWS partnership ecosystems, public sector engagement, and designing commercially viable transformation strategies that combine technology, services and operational efficiency.

Known for his ability to thinik differently around business challanges, he focuses on creating scalable, innovative solutions that help organizations modernize operations, improve service delivery, and accelarate digital transformation initiatives.

    Reach Out Us


    Your name

    Your email

    Subject

    Your message