Search code examples
phplaravellaravel-5

Laravel ignore mutators


I am using Laravel's Mutator functionality and I have the following Mutator:

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

However I need to Ignore this Mutator in some cases. Is there any way to achieve this


Solution

  • 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);
        }
    }
    

    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;