Laravel - Mutators / Casts - Array Object And Collection Casting

Although the standard array cast is sufficient for many applications, it does have some disadvantages. Since the array cast returns a primitive type, it is not possible to mutate an offset of the array directly. For example, the following code will trigger a PHP error:

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

To solve this, Laravel offers an AsArrayObject cast that casts your JSON attribute to an ArrayObject class. This feature is implemented using Laravel's custom cast implementation, which allows Laravel to intelligently cache and transform the mutated object such that individual offsets may be modified without triggering a PHP error. To use the AsArrayObject cast, simply assign it to an attribute:

    
    use Illuminate\Database\Eloquent\Casts\AsArrayObject;
    
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'options' => AsArrayObject::class,
    ];
	

Similarly, Laravel offers an AsCollection cast that casts your JSON attribute to a Laravel Collection instance:

    
    use Illuminate\Database\Eloquent\Casts\AsCollection;
    
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'options' => AsCollection::class,
    ];