本文介绍了Laravel忽略变异者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Laravel的Mutator功能,并且具有以下Mutator:
I am using Laravel's Mutator functionality and I have the following Mutator:
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
但是在某些情况下,我需要忽略此Mutator.有什么办法可以做到这一点
However I need to Ignore this Mutator in some cases.Is there any way to achieve this
推荐答案
在模型中设置一个公共变量,例如$ preventAttrSet
Set a public variable in model, e.g $preventAttrSet
public $preventAttrSet = false;
public function setFirstNameAttribute($value) {
if ($this->preventAttrSet) {
// Ignore Mutator
$this->attributes['first_name'] = $value;
} else {
$this->attributes['first_name'] = strtolower($value);
}
}
现在,当您要根据情况忽略Mutator时,可以将public变量设置为true
Now you can set the public variable to true when want to Ignore Mutator according to your cases
$user = new User;
$user->preventAttrSet = true;
$user->first_name = 'Sally';
echo $user->first_name;
这篇关于Laravel忽略变异者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!