When the field is updating, the mutator does not work
I have a mutator in model:
use Illuminate\Support\Str;
class Filter extends Model
{
protected $fillable = ['slug', 'title', 'deleted_at'];
protected function setSlugAttribute($value)
{
$this->attributes['slug'] = Str::slug($value);
}
}
I'm trying to update the entry:
$data = [
'slug' => 'Foo',
'title' => 'Bar'
];
$item = Filter::query()
->where('id', $id)
->update($data);
Result:
[
"id" => 2
"slug" => "Foo"
"title" => "Bar"
"created_at" => "2018-01-30 12:48:29"
"updated_at" => "2018-02-21 12:47:57"
"deleted_at" => null
]
You're doing a database query. You need to load the model.
$item = Filter::find($id)->update($data);
@BrandonSurowiec is right.
update is working on DB layer when you call it on Builder instead of Model and it doesn't consider any Eloquent features like mutators and events.
Probably, I have read the documentation poorly. Thank you!
Most helpful comment
You're doing a database query. You need to load the model.