laravel雄辩的模型更新事件未触发 [英] laravel Eloquent model update event is not fired

查看:39
本文介绍了laravel雄辩的模型更新事件未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

圣诞快乐!

我是Laravel的新手.刚遇到一个初学者的问题,当我尝试使用服务提供商和模型事件来记录更新信息时.

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.

遵循在线文档: https://laravel.com/docs/5.3/eloquent#事件

将所有代码放在一起后,我发现仅在创建使用时触发模型事件,而在编辑用户时从不记录任何内容.

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.

我错过了什么吗?感觉$ 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()
    {
        //
    }
}

推荐答案

您需要从数据库中检索用户,然后保存该用户以触发事件.例如:

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

这不会触发更新事件:

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

这将触发更新事件:

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

这篇关于laravel雄辩的模型更新事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆