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.
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
Step 3: Create a Model and Migration
Begin by generating an Employee model and its corresponding migration using Artisan commands:
php artisan make:model Employee -m
Step 4: Add Migration Code
Open the generated migration file and add the code below to define the table and its columns, including those that we will apply encryption to later on.
As stated in the documentation on Eloquent encrypted casting all columns that will be encrypted need to be of type ‘text’ or larger, so make sure you use the correct type in your migration!
database/migrations/2023_12_10_172859_create_employees_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('name'); // The 'name' column which we won't encrypt
$table->text('email'); // The 'email' column, which we will encrypt
$table->text('phone'); // The 'phone' column, which we will encrypt
$table->text('address'); // The 'address' column, which we will encrypt
// Other columns...
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('employees');
}
};
Step 5: Run the Migration
Run the migration to create the ‘employees’ table:
php artisan migrate
Step 6: Add encrypted
casts to Model
Open the Employee model and add the code below to specify the attributes to be encrypted using the $casts
property. We’ll also define a fillable array to make sure fields will support mass assignment to ease creation of models with data:
app/Models/Employee.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $casts = [
'email' => 'encrypted',
'phone' => 'encrypted',
'address' => 'encrypted',
// Other sensitive attributes...
];
protected $fillable = [
'name',
'email',
'phone',
'address',
];
// Other model configurations...
}
Step 7: Saving and Retrieving Encrypted Data
Once configured, saving and retrieving data from the encrypted attributes remains unchanged. Eloquent will automatically handle the encryption and decryption processes.
To test this out I like to use Laravel tinker. To follow along open Tinker by running:
php artisan tinker
Then paste the following code:
use App\Models\Employee;
$employee = Employee::create([
'name' => 'Paul Atreides',
'email' => '[email protected]', // Data is encrypted before storing
'phone' => '123-456-7890', // Encrypted before storing
'address' => 'The Keep 12', // Encrypted before storing
]);
echo $employee->email; // Automatically decrypted
echo $employee->phone; // Automatically decrypted
echo $employee->address; // Automatically decrypted
The output shows the Laravel Eloquent was able to decrypt the contents properly:
> echo $employee->email;
[email protected]
> echo $employee->phone;
123-456-7890
> echo $employee->address;
The Keep 12
Conclusion
By using Laravel Eloquent’s built-in cast “encrypted” we can easily add a layer of security that applies encryption to sensitive data.
In our example we learned how to encrypt sensitive data of employee’s like email, address and phone and demonstrated how the application can still use them.
Now you can apply this technique to your own applications and ensure the privacy of your users is up to todays standards. Happy coding!
References
- Eloquent Mutator: Encrypted Casting (Laravel Documentation)
- Encryption Configuration (Laravel Documentation)