Create Your Own Custom Casts in Laravel


- Create Custom Casts in Laravel
- Step 1: Create a Custom Cast Class
- Step 2: Use the Custom Cast in a Model
- Additional Notes
Create Custom Casts in Laravel
In Laravel, Eloquent provides a simple way to cast attributes to common data types like integers, booleans, arrays, and even objects. But sometimes, the built-in casts aren’t enough. That’s where custom casts come in. They allow you to define your own logic for how a model attribute should be stored and retrieved.
In this post, we’ll walk through how to create and use a custom cast in Laravel.
Step 1: Create a Custom Cast Class
To create a custom cast, you need to implement the CastsAttributes
interface. This interface requires two methods:
-
get($model, $key, $value, $attributes)
– used when retrieving the value from the database -
set($model, $key, $value, $attributes)
– used when storing the value into the database
Here’s an example of a custom cast that encrypts and decrypts a value:
namespace App\Casts; use Illuminate\Contracts\Database\Eloquent\CastsAttributes;use Illuminate\Support\Facades\Crypt; class Encrypted implements CastsAttributes{ public function get($model, $key, $value, $attributes): string { return Crypt::decryptString($value); } public function set($model, $key, $value, $attributes): string { return Crypt::encryptString($value); }}
This cast will automatically encrypt a value before saving it to the database and decrypt it when retrieving it.
Step 2: Use the Custom Cast in a Model
Once your custom cast is ready, you can assign it to a model attribute using the $casts
property:
use App\Casts\Encrypted; class User extends Model{ protected $casts = [ 'secret' => Encrypted::class, ];}
Now, whenever you access $user->secret
, the value will be decrypted, and when you set $user->secret = 'value'
, it will be encrypted before saving.
Additional Notes
- The custom cast must be a class that implements
CastsAttributes
. - Custom casts give you full control over how attributes behave.
Stay Updated.
I'll you email you as soon as new, fresh content is published.
Latest Posts