DEV Community

Cover image for How to Encrypt and Decrypt Model Data Using Casts in Laravel
Saddam Hossain
Saddam Hossain

Posted on

How to Encrypt and Decrypt Model Data Using Casts in Laravel

How to Encrypt and Decrypt Model Data Using Casts in Laravel. Using the Eloquent ‘encrypted’ cast type, you can instruct Laravel to encrypt specific attributes before storing them in the database. Later, when accessed through Eloquent, the data is automatically decrypted for your application to use. You Can Learn Laravel 11 Livewire Wizard Multi Step Form Tutorial

How to Encrypt and Decrypt Model Data Using Casts in Laravel
Encrypting fields in a database enhances security by scrambling sensitive data. This measure shields information like emails, addresses, and phone numbers, preventing unauthorized access and maintaining confidentiality even if data is exposed.

In this guide you’ll learn to use Eloquent’s built-in ‘encrypted’ cast to encrypt sensitive data within an ‘Employee’ model to ensure personal data is stored securely.

Important note: Encryption and decryption in Laravel are tied to the APP_KEY found in the .env file. This key is generated during the installation and should remain unchanged. Avoid running ‘php artisan key:generate‘ on your production server. Generating a new APP_KEY will render any encrypted data irretrievable. You Can Learn more Laravel 11 Livewire Wizard Multi Step Form Tutorial

While keeping that in mind. Let’s get started and apply encryption!

How to Encrypt and Decrypt Model Data Using Casts in Laravel Example

Step 1: Create a Laravel Project

Begin by creating a new Laravel project if you haven’t done so already. Open your terminal and run:

composer create-project laravel/laravel model-encrypt
cd model-encrypt
Enter fullscreen mode Exit fullscreen mode

Step 2: Add Database Credentials to the .env file

Open the .env file in your project and add the database credentials you wish to use:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your-db
DB_USERNAME=your-db-user
DB_PASSWORD=your-db-password
Enter fullscreen mode Exit fullscreen mode

Read More

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more