简体   繁体   中英

Model observer is not firing while updating

I have an issue while trying to use an observer that it doesn't fire the observer only in the updated case. it works fine in other cases..

I had some research about it and I found some solutions, such as calling the update method directly from the model, not in a repository, but unfortunately, it didn't work for me. the solution I found: https://github.com/laravel/framework/issues/11777#issuecomment-170388067

UserObserver
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::observe(UserObserver::class);
    }
}

and here's my AppServiceProvider :

// First try
$user = User::findOrFail($id);
$user->update($data);
// Second try
User::findOrFail($id)->update($data);

I called the update method in my controller like this:

array [
  "nationality_id" => "1"
  "birth_date" => "2013-05-26"
  "gender" => "1"
  "job_title" => "Pariatur Sit provideeee"
  "salary" => "5100"
]

this an example of my $data array:

 array [ "nationality_id" => "1" "birth_date" => "2013-05-26" "gender" => "1" "job_title" => "Pariatur Sit provideeee" "salary" => "5100" ]

Laravel checks if the model has actually been changed before firing updates, so make sure you change the model before saving or updating it.

Additionally, updating events are only fired when you update your model directly.

That means this will fire an event:

$user = User::findOrFail($id);
$user->update($data);

While something like this will not

User::where('id', $id)->update($data);

This is done by design, since using an update query could update millions of rows at once, making it unrealistic to fire events for all of them.

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