Framework: [5.6] When the field is updating, the mutator does not work

Created on 21 Feb 2018  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 5.6.3
  • PHP Version: 7.2.0
  • Database Driver & Version: MySQL 5.7

Description:

When the field is updating, the mutator does not work

Steps To Reproduce:

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
  ]

Most helpful comment

You're doing a database query. You need to load the model.

$item = Filter::find($id)->update($data);

All 3 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iivanov2 picture iivanov2  路  3Comments

shopblocks picture shopblocks  路  3Comments

digirew picture digirew  路  3Comments

RomainSauvaire picture RomainSauvaire  路  3Comments

felixsanz picture felixsanz  路  3Comments