Saddam Hossain
Posted on November 17, 2024
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
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
Posted on November 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.