Created
October 4, 2021 16:30
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
// ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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