Laravel - Mutators / Casts - Castables
You may want to allow your application's value objects to define their own custom cast classes. Instead of attaching the custom cast class to your model, you may alternatively attach a value object class that implements the Illuminate\Contracts\Database\Eloquent\Castable
interface:
use App\Models\Address;
protected $casts = [
'address' => Address::class,
];
Objects that implement the Castable
interface must define a castUsing
method that returns the class name of the custom caster class that is responsible for casting to and from the Castable
class:
When using Castable
classes, you may still provide arguments in the $casts
definition. The arguments will be passed to the castUsing
method:
use App\Models\Address;
protected $casts = [
'address' => Address::class.':argument',
];