Laravel - Mutators / Casts - Array Json Serialization

When an Eloquent model is converted to an array or JSON using the toArray and toJson methods, your custom cast value objects will typically be serialized as well as long as they implement the Illuminate\Contracts\Support\Arrayable and JsonSerializable interfaces. However, when using value objects provided by third-party libraries, you may not have the ability to add these interfaces to the object.

Therefore, you may specify that your custom cast class will be responsible for serializing the value object. To do so, your custom cast class should implement the Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes interface. This interface states that your class should contain a serialize method which should return the serialized form of your value object:

     * Get the serialized representation of the value.
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @return mixed
    public function serialize($model, string $key, $value, array $attributes)
        return (string) $value;