Saad Saad - 9 months ago 67
PHP Question

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

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download