Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel Eloquent model update event is not fired

Merry Christmas guys!

I am new to Laravel. Just had a beginner's question, when I am trying to use service provider and model event to log the update information.

Was following the online doc: https://laravel.com/docs/5.3/eloquent#events

After put all code together, I find that the model event only fire when create the use but never log anything when I edit the user.

Did I miss anything? Feel like the $user didn't get assigned properly. Where is it from? from other service provider?

Any explanation or hint will be appreciated!

<?php

namespace App\Providers;

use App\User;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::creating(function ($user) {
            Log::info('event creating');
        });

        User::created(function ($user) {
            Log::info('event created');
        });

        User::updating(function ($user) {
            Log::info('event updating');
        });

        User::updated(function ($user) {
            Log::info('event updated');
        });

        User::saving(function ($user) {
            Log::info('event saving');
        });

        User::saved(function ($user) {
            Log::info('event saved');
        });

        User::deleting(function ($user) {
            Log::info('event deleting');
        });

        User::deleted(function ($user) {
            Log::info('event deleted');
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
like image 735
northblue Avatar asked Dec 23 '16 04:12

northblue


2 Answers

You need to retrieve the user from the database and then save that user in order to fire the event. For example:

This will NOT fire the update event:

User::where('id', $id)->update(['username' => $newUsername]);

This will fire the update event:

User::find($id)->update(['username' => $newUsername]);
like image 118
Eric Tucker Avatar answered Oct 17 '22 08:10

Eric Tucker


Possible reasons:

  1. The row is not updated at all - no changes. Hence not firing, and

  2. You used update. Check the docs here: https://laravel.com/docs/5.3/eloquent#updates

When issuing a mass update via Eloquent, the saved and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.

like image 21
Lionel Chan Avatar answered Oct 17 '22 09:10

Lionel Chan