简体   繁体   中英

Laravel's Model observer class is not working when updating using query builder

I am explaining my issue with an example.

My model class is User and observer class is UserObserver .

I have added some code in the updated method of UserObserver that will run everytime the User model update function is used. For example updated method in the UserObserver (below) should get called whenever an update happen in User record.

class UserObserver{
   function updated($userModel)
   {
      //Send mail code
   }
}

The code in the UserObserver works when User data update like shown below:

User::find(2)->update(['name'=>'Update Name']);

However, the code in the UserObserver won't run when User data is updated in the following way:

User::where('id', 2)->update(['name'=>'Update Name']);

When I debug I can understand that User::find(2) return User model object and User::where('id', 2) will return a Builder object. So, how can I make use of our observer class method regardless of whether it is updated using User Model object or Builder object?

The issue is, I do have an existing application, some of the models are updating like User::where('id', 2)->update(['name'=>'Update Name']); . It is a difficult task to modify update statement to User::find(2)->update(['name'=>'Update Name']); .

Try as below:

User::where('id', 2)->first()->update(['name'=>'Update Name']);

The one problem with this code is that if you don't have the user with the id = 2 in your database then you will get null and you will get and exception may be as calling update on undefined entity.

So you can avoid this as below:

$user = User::where('id', 2)->first(); if(!empty($user)) { $user->getModel()->update(['name'=>'Update Name']); }

Dear Observer not depend on Model object or Builder Object. It works on both statements...

User::find(2)

and

User::where('id', 2)

I am facing the same problem yesterday, but i install last Monday revisionable package and when i explore that package, its work on my code "User::where('id', 2)" .

Actually i am placing my code in updating() method, but when i place the same code in saving() method its work for me...

User model class should have a fillable variable.

class User extends Model
{
   protected $fillable = ['name'];
}

Try to add the first() method after where clause.

User::where('id', 2)->first()->update(['name'=>'Update Name']);

Or twist where clause to get User model object.

$user = User::where('id', 2)->first();
if(!$user) {
     $user->update(['name'=>'Update Name']);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM