在 laravel 5.3 中使用带访问器的强制转换

Nik*_*nko 9 php json casting laravel

我想用laravel(5.3)能言善辩的$casts属性一样protected $casts = ["example" => "object"]getExampleAttribute访问,但因为它似乎访问丢弃的$casts行为。这对我来说至关重要,因为我想将 JSON 对象存储在数据库中并为其设置默认值,例如:

public function getExampleAttribute($value) {
    if($value === NULL) 
        return new \stdclass();
    return $value
}
Run Code Online (Sandbox Code Playgroud)

所以我永远不会在我的视图中得到 NULL 值。有没有办法比在访问器和修改器中显式实现强制转换逻辑更容易?

Tri*_*rip 11

如果您希望该字段明确遵循$casts定义,则以下解决方案有效。您只需要从访问器修改器内部手动调用 cast 函数:

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;
}
Run Code Online (Sandbox Code Playgroud)

这种方法假设您将来可能会更改演员表,但是如果您知道它始终是一个数组/json 字段,那么您可以castAttribute()像这样替换调用:

public function getExampleAttribute($value)
{
    // translate object from Json storage
    $example = $this->fromJson($value, true)

    /** set defaults for $example **/

    return $example;
}
Run Code Online (Sandbox Code Playgroud)