I want to use laravel (5.3) eloquent's $casts
attribute like protected $casts = ["example" => "object"]
with getExampleAttribute
accessor, but as it seems accessor discards the $casts
behaviour. It's crucial for me since I want to store JSON object in database and have a default value for it, e.g:
public function getExampleAttribute($value) {
if($value === NULL)
return new \stdclass();
return $value
}
so I would never get NULL values in my views. Is there a way to do it easier than just implementing casts logic within accessor and mutator explicitly?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With