Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 686
Saad Avatar asked May 08 '17 07:05

Saad


3 Answers

If you need to skip Eloquent Model mutators once in a while (for example in unit tests) you should use setRawAttributes():

$model->setRawAttributes([
  'first_name' => 'Foobar',
]);
like image 80
trm42 Avatar answered Oct 17 '22 14:10

trm42


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;
like image 20
Dinoop Avatar answered Oct 17 '22 15:10

Dinoop


Whereas the answers provided seems to work, there is a method in Laravel to access the original value:

$service->getOriginal('amount')

See this post: Example of getOriginal()

Api: API Documentation

like image 19
Quins Avatar answered Oct 17 '22 14:10

Quins