2017-05-08 78 views
0

我使用Laravel的赋值函数功能,我有以下的赋值函数:Laravel忽略存取器

public function setFirstNameAttribute($value) 
{ 
    $this->attributes['first_name'] = strtolower($value); 
} 

不过,我需要忽略此赋值函数在某些情况下。 有没有办法实现这个

+0

如果不总是需要这个功能,当然它应该被移动到需要的地方,并删除了突变的功能? –

回答

3

设置一个公共变量模型,如:$ 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); 
    } 
} 

现在需要根据个人情况

$user = new User; 
$user->preventAttrSet = true; 
$user->first_name = 'Sally'; 
echo $user->first_name; 
0

您可以设置该属性本身:

$model->attributes['first_name'] = 'New First Name With Capitals'; 

这绕过了存取器。

+0

PS。我必须同意奈杰尔仁所做的评论。如果你并不总是需要mutator,那么看看你是否可以重新设计你的流程,因为mutators用于总是改变数据。 –

1

到忽略赋值函数时,你可以设置公共变量设置为true而问题的答案提供似乎有效,Laravel有一种方法可以访问原始值:

$service->getOriginal('amount') 

看到这个帖子: Example of getOriginal()

API: API Documentation