Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using casts with accessor in laravel 5.3

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?

like image 445
Nikolay 'Alagunto' Tkachenko Avatar asked Feb 14 '17 16:02

Nikolay 'Alagunto' Tkachenko


1 Answers

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;
}
like image 71
Trip Avatar answered Oct 24 '22 11:10

Trip