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. 

Piyush Solanki

PHP Tech Lead & Backend Architect

10+ years experience
UK market specialist
Global brands & SMEs
Full-stack expertise

Core Technologies

PHP 95%
MySQL 90%
WordPress 92%
AWS 88%
  • Backend: PHP, MySQL, CodeIgniter, Laravel
  • CMS: WordPress customization & plugin development
  • APIs: RESTful design, microservices architecture
  • Frontend: React, TypeScript, modern admin panels
  • Cloud: AWS S3, Linux deployments
  • Integrations: Stripe, SMS/OTP gateways
  • Finance: Secure payment systems & compliance
  • Hospitality: Booking & reservation systems
  • Retail: E-commerce platforms & inventory
  • Consulting: Custom business solutions
  • Food Services: Delivery & ordering systems
  • Modernizing legacy systems for scalability
  • Building secure, high-performance products
  • Mobile-first API development
  • Agile collaboration with cross-functional teams
  • Focus on operational efficiency & innovation

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. With extensive experience in the UK market and across multiple sectors, Piyush is passionate about helping SMEs scale technology teams and accelerate innovation through backend excellence.