'Laravel - Attribute casting does not cast serialised value to array

I have a model in which I have the following cast:

 protected $casts = [
    'formatted_criteria' => 'array'
 ];

It is stored in the database as a serialized array but when I retrieve it why doesn't it automatically revert back to an array?

Instead I'm having to use an accessor to unserialize back to an array.



Solution 1:[1]

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Serialize implements CastsAttributes { public function get($model, $key, $value, $attributes) { return serialize($value); }

public function set($model, $key, $value, $attributes)
{
    return unserialize($value);
}

}

protected $casts = [
    'package_document' => Serialize::class,
    'package_dates' => Serialize::class,
];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rezaseo hamimohajer