Laravel - Mutators / Casts - Value Object Casting
You are not limited to casting values to primitive types. You may also cast values to objects. Defining custom casts that cast values to objects is very similar to casting to primitive types; however, the set
method should return an array of key / value pairs that will be used to set raw, storable values on the model.
As an example, we will define a custom cast class that casts multiple model values into a single Address
value object. We will assume the Address
value has two public properties: lineOne
and lineTwo
:
$value->lineOne,
'address_line_two' => $value->lineTwo,
];
}
}
When casting to value objects, any changes made to the value object will automatically be synced back to the model before the model is saved:
use App\Models\User;
$user = User::find(1);
$user->address->lineOne = 'Updated Address Value';
$user->save();
If you plan to serialize your Eloquent models containing value objects to JSON or arrays, you should implement theIlluminate\Contracts\Support\Arrayable
andJsonSerializable
interfaces on the value object.