Using casts with accessor in laravel 5.3
If you want the field to explicitly follow the $casts
definition, the following solution works. You just need to manually call the cast function from inside an accessor mutator:
public function getExampleAttribute($value){ // force the cast defined by $this->casts because // this accessor will cause it to be ignored $example = $this->castAttribute('example', $value); /** set defaults for $example **/ return $example;}
This method sort of assumes that you might change the cast in the future, but if you know it's always going to be an array/json field then you can substitute the castAttribute()
call like this:
public function getExampleAttribute($value){ // translate object from Json storage $example = $this->fromJson($value, true) /** set defaults for $example **/ return $example;}