Laravel - Mutators / Casts - Array And Json Casting

The array cast is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:


Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options attribute, the given array will automatically be serialized back into JSON for storage:

    use App\Models\User;
    $user = User::find(1);
    $options = $user->options;
    $options['key'] = 'value';
    $user->options = $options;

To update a single field of a JSON attribute with a more terse syntax, you may use the -> operator when calling the update method:

    $user = User::find(1);
    $user->update(['options->key' => 'value']);