Skip to content

Instantly share code, notes, and snippets.

@fahmiegerton
Created October 4, 2021 16:30
Show Gist options
  • Save fahmiegerton/90797448f034769c8daff315aa309020 to your computer and use it in GitHub Desktop.
Save fahmiegerton/90797448f034769c8daff315aa309020 to your computer and use it in GitHub Desktop.
Laravel Eloquent - Ignore mutators in some case situation (https://stackoverflow.com/a/43849449/4705820)
<?php
// ...
public function update(MyModel $m, $id) {
$m->$preventAttrSet = true; // this doesn't work, it will reset to false again
$data = $m->with('relation')->findOrFail($id)->ignoreMutators(); // this work and will ignore the mutators
return view('some.view', $data);
}
// ...
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
use HasFactory;
// other properties
public $preventAttrSet = false;
public function setFirstNameAttribute($value) {
if ($this->preventAttrSet) {
// Ignore Mutator
$this->attributes['first_name'] = $value;
} else {
$this->attributes['first_name'] = strtolower($value);
}
}
public function ignoreMutators(bool $ignore = true) {
$this->preventAtrrSet = $ignore;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment