修改Laravel模型的所有属性

rev*_*evo 2 laravel laravel-5.1

访问者将完美地在单个属性上完成他们的工作,但我需要一种方法来自动地对所有属性执行Accessor/Getter作业.

目的是我想在获取属性时替换一些字符/数字,然后将它们打印出来.我可以从控制器内部手动完成,但我认为从模型端自动获取它会很棒.

像重写getAttributes()方法:

public function getAttributes()
{
    foreach ($this->attributes as $key => $value) {
        $this->attributes[$key] = str_replace([...], [...], $value);
    }
    return $this->attributes;
}
Run Code Online (Sandbox Code Playgroud)

但我每次都要在模特身上打电话 $model->getAttributes();

有什么方法可以自动干燥吗?

Tim*_*Uum 5

尝试类似的东西:

public function getAttribute($key)
{
    if (array_key_exists($key, $this->attributes) || $this->hasGetMutator($key)) {
        if($key === 'name') return 'modify this value';
        return $this->getAttributeValue($key);
    }

    return $this->getRelationValue($key);
}
Run Code Online (Sandbox Code Playgroud)

它完全覆盖了默认方法,所以要小心一点.

编辑

另请查看:http://laravel.com/docs/5.1/eloquent-mutators