laravel-encrypt-and-decrypt

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. 

Author: Piyush Solanki

Piyush is a seasoned PHP Tech Lead with 10+ years of experience architecting and delivering scalable web and mobile backend solutions for global brands and fast-growing SMEs. He specializes in PHP, MySQL, CodeIgniter, WordPress, and custom API development, helping businesses modernize legacy systems and launch secure, high-performance digital products.

He collaborates closely with mobile teams building Android & iOS apps , developing RESTful APIs, cloud integrations, and secure payment systems using platforms like Stripe, AWS S3, and OTP/SMS gateways. His work extends across CMS customization, microservices-ready backend architectures, and smooth product deployments across Linux and cloud-based environments.

Piyush also has a strong understanding of modern front-end technologies such as React and TypeScript, enabling him to contribute to full-stack development workflows and advanced admin panels. With a successful delivery track record in the UK market and experience building digital products for sectors like finance, hospitality, retail, consulting, and food services, Piyush is passionate about helping SMEs scale technology teams, improve operational efficiency, and accelerate innovation through backend excellence and digital tools.

View all posts by Piyush Solanki >