Custom eloquent casting in Laravel 7 is another cool features. This features will give you the ability to add your own custom casts.

Laravel has a variety of built-in, helpful cast types; however, you may occasionally need to define your own cast types.
If you remember, we used to use casting in our Eloquent models like so,

protected $casts = [
'email_verified_at' => 'datetime',
];

Now what if we need to cast an attribute to some custom type.

Creating a custom Eloquent Cast

You may now accomplish this by defining a class that implements the CastsAttributes interface. Classes that implement this interface must define a get and set methods. The get method is responsible for transforming a raw value from the database into a cast value, while the set method should transform a cast value into a raw value that can be stored in the database. As an example, we will re-implement the built-in json cast type as a custom cast type:

<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Json implements CastsAttributes
{
    /**
     * Cast the given value.
     */
    public function get($model, $key, $value, $attributes)
    {
        return json_decode($value, true);
    }

    /**
     * Prepare the given value for storage.
     */
    public function set($model, $key, $value, $attributes)
    {
        return json_encode($value);
    }
}

Once we have defined a custom cast type, we can attach it to a model attribute using its class name:

protected $casts = [
        'options' => Json::class,
    ];

You may also Like