Back to dictionary

Custom Eloquent Casts

Custom Eloquent Casts is a powerful feature in Laravel, a key component of the VILT stack, that allows developers to transform attribute values when interacting with a model. Essentially, it provides a convenient way to convert one type of value to another, such as a string to a JSON object, when retrieving or setting the value on a model.

For instance, if you have a JSON column in your database and you want to interact with it as an array in your Laravel application, you can use a cast to automatically convert the JSON to an array and vice versa. This can be incredibly useful when dealing with complex data structures or when you need to ensure data consistency across your application.

In Laravel, you can define a cast using the $casts property on your model. For example, if you have a 'settings' column that you want to cast to an array, you would define it like this:

protected $casts = [
    'settings' => 'array',
];

However, Laravel also allows you to define custom casts if the built-in ones don't meet your needs. Custom casts are classes that define a "set" and a "get" method. The "set" method is used to transform a value before it's stored in the database, while the "get" method is used to transform a value after it's retrieved from the database.

For example, if you wanted to create a custom cast that encrypts and decrypts a value, you could do so like this:

class EncryptedCast implements CastsAttributes

{
    public function get($model, $key, $value, $attributes)
    {
        return decrypt($value);
    }

    public function set($model, $key, $value, $attributes)

    {
        return encrypt($value);
    }
}

Then, you would apply this cast to a model attribute like this:

protected $casts = [
    'secret' => EncryptedCast::class,
];

This feature can be particularly useful when working with a tool like Craftable PRO, which leverages the power of Laravel to generate robust admin panels. By using custom eloquent casts, you can ensure that your data is always in the correct format and state, regardless of how it's stored in the database. This can help to reduce bugs, improve data integrity, and make your code easier to work with.