thmspl
thmspl

Reputation: 2495

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

I'm trying to catch the model event updating in laravel 7 but it doesn't fire.

This is the place where the model get's changed:

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

  return new Resource($model);
}

I also tried this to update the values:

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

And here I'm trying to catch the event within the bill model:

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

What am I doing wrong?

Upvotes: 0

Views: 2830

Answers (1)

Remul
Remul

Reputation: 8252

You have to call parent::boot() at the start of your boot method:

protected static function boot() {

  parent::boot();

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

Laravel 7 added a booted method to make it easier:

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.

From the 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) {
            //
        });
    }
}

Upvotes: 2

Related Questions