
Laravel 11 Using Custom Casts for Eloquent Models - Step by StepGuide
Custom casts in Laravel helps you to transform the attributes whey they are accessed or stored in DB. They help us by maintaining our attributes in a consistent format .Custom casts are particularly useful when dealing with JSON data, encrypted fields, or any non-primitive data types.
To define a custom cast, you first create a class that implements the CastsAttributes interface.
Step-by-Step Guide to Creating and Using Custom Casts
Create a Custom Cast Class
The first step in creating a custom cast is to define a class that implements the CastsAttributes interface. This interface requires two methods : get and set.
The get method is responsible for transforming the raw value from the database into a format that your application can work with.
The set method is used to prepare the attribute for storage in the database. This method typically involves converting the attribute to a format that can be stored in the database.
Register the Custom Cast in Model
Once the custom cast class is created, you need to register it in your Eloquent model by adding it to the $castsproperty.
By adding 'settings' => Json::class to the $casts property, Laravel will automatically use the Json cast class to transform the settings attribute whenever it is accessed or modified.
When you set the settings attribute, the set method of the Json cast class is called, encoding the array to JSON before storing it in the database. When you access the settings attribute, the get method is called, decoding the JSON back to an array.
Advanced Custom Casts
Custom casts are not limited to simple transformations. You can perform more complex logic as needed.
For example, you might want to encrypt sensitive data before storing it and decrypt it when retrieving it.
Register the cast in model:
Now, whenever you set the secret attribute, it will be encrypted before storage, and decrypted when accessed.
Combining Multiple Casts
You can also combine multiple custom casts within a single model. This allows you to handle different attributes in different ways.