Question

It seems that default values defined in the $attributes property are not being mutated before saving to the database?

I have this setup:

protected $attributes = array(
    'data' => array();    
);

public function getDataAttribute($value)
{
    return unserialize($value);
}
public function setDataAttribute($value)
{
    $this->attributes['data'] = serialize($value);
}

All I get is database field filled with literally 'Array' and a preg_replace error. Upon specifying the default attribute in an overridden save() method it does get mutated.

Can anyone confirm this and/or has suggestions?

Thanks.

Was it helpful?

Solution

You are assigning a default variable on the object itself, which is outside the function of a mutator.

The best option is probably to include the default in the constructor of the model, so they are called and mutated when the object is created. I think something like this should work:

function __construct($attributes = array()) {
    parent::__construct($attributes);
    $this->data = array();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top