Eloquent 模型事件“更新”未在 laravel 7 中触发

Eloquent model event `updating` isn't firing in laravel 7

我试图在 laravel 7 中捕获模型事件 updating,但它没有触发。

这是模型更改的地方:

public function update(Request $request, Model $model)  {
  $model->update($request->input());

  return new Resource($model);
}

我也试过这个来更新值:

public function update(Request $request, Model $model)  {
  $model->attribute1 = $request->get('value1');
  $model->attribute2 = $request->get('value2');
  $model->attribute3 = $request->get('value3');
  $model->save();

  return new Resource($model);
}

这里我试图在账单模型中捕获事件:

protected static function boot() {
  static::updating(function ($model) {
      // code
  });
}

我做错了什么?

您必须在启动方法开始时调用 parent::boot():

protected static function boot() {

  parent::boot();

  static::updating(function ($model) {
      // code
  });
}

Laravel 7 添加了一个引导方法以使其更容易:

Adding booting / booted methods to Model

Currently, users who extend the boot method to add event listeners on model events must remember to call parent::boot() at the start of their method (or after). This is often forgotten and causes confusion for the user. By adding these simple place-holder extension points we can point users towards these methods instead which do not require them to call any parent methods at all.

来自docs

Instead of using custom event classes, you may register Closures that execute when various model events are fired. Typically, you should register these Closures in the booted method of your model:

<?php

namespace App;

use App\Scopes\AgeScope;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::created(function ($user) {
            //
        });
    }
}