laravel Eloquent model update event is not fired

邮差的信 提交于 2020-12-02 06:49:08

问题


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()
    {
        //
    }
}

回答1:


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]);



回答2:


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.



来源:https://stackoverflow.com/questions/41295032/laravel-eloquent-model-update-event-is-not-fired

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!