修改Laravel模型的所有属性

修改Laravel模型的所有属性,laravel,laravel-5.1,Laravel,Laravel 5.1,访问器将在单个属性上完美地完成它们的工作,但我需要一种方法来对所有属性自动执行访问器/获取器工作 其目的是在获取属性时替换一些字符/数字,然后将它们打印出来。我可以从控制器内部手动完成,但我认为从模型侧自动完成会很好 类似于重写getAttributes()方法: public function getAttributes() { foreach ($this->attributes as $key => $value) { $this->attribu

访问器将在单个属性上完美地完成它们的工作,但我需要一种方法来对所有属性自动执行访问器/获取器工作

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

类似于重写
getAttributes()
方法:

public function getAttributes()
{
    foreach ($this->attributes as $key => $value) {
        $this->attributes[$key] = str_replace([...], [...], $value);
    }
    return $this->attributes;
}
但是我每次都必须在model
$model->getAttributes()上调用它

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

试试以下方法:

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);
}
它完全覆盖了默认方法,所以要小心一点

编辑


另请查看:

如何在创建和更新每个事件时运行它。所以你可以这样做:

public function boot()
    {
        Model::creating(function ($model)
            return $model->getAttributes();   //or $this->getAttributes()
        });
        Model::updating(function ($model)
            return $model->getAttributes();   //or $this->getAttributes()
        });
    }

我将采用以下方法并覆盖模型获取方法:

public function __get($key)
{
    $excluded = [
        // here you should add primary or foreign keys and other values,
        // that should not be touched.
        // $alternatively define an $included array to whitelist values
        'foreignkey', 
    ];

    // if mutator is defined for an attribute it has precedence.
    if(array_key_exists($key, $this->attributes)
       && ! $this->hasGetMutator($key) && ! in_array($key, $excluded))  {
        return "modified string";
    }

    // let everything else handle the Model class itself
    return parent::__get($key);
}

}

重写构造函数并使用父项::\u construct()如何?或者添加新类扩展模型使用构造,让模型扩展该新类,使其应用于所有对象。@TimvanUum实际上我这样做了,但我认为应该有问题,因为它根本不会影响结果!奇怪的是,我自己也试过了,确实不起作用。即使再次调用fill方法。覆盖
getAttribute
的绝佳解决方案。但是,设置值时会调用变量,这不是本文的目的。请您进一步解释一下您的评论。或者澄清为什么这个解决方案不起作用?@shock\u gone\u wild你能解释一下为什么这个解决方案不起作用吗?你有错误吗?你没有得到你想要的结果吗?可以将此函数添加到特定的模型类(如User)或创建一个扩展模型的新类(CustomBaseModel),并将其添加到该类中,然后让模型扩展该新类。将if($key=='name')更改为要更改的内容或删除以更改所有内容。使用:$this->getAttributeValue($key);要修改值哦,对不起,我应该更清楚。我特别回答了这句话:“但是,在设置值时会调用变量,这不是本文的目的。”您的解决方案没有任何问题,尽管我会优先考虑覆盖magic _get()方法。我最终在自定义模型中使用了您的解决方案,并对其进行了扩展,但在用户模型上除外。
model::creating()。我不会靠存钱,而是靠得到钱。我说的是访问器而不是变异器。