How to implement eloquent 'saving' event for all models , not individually

我与影子孤独终老i 提交于 2019-12-06 15:59:43

Listen for the Eloquent creating event that is fired. It is a 'string' event still not an object so you can do some ... wildcard matching here.

This is the string of the events that are fired from Eloquent:

"eloquent.{$event}: ".static::class

So you could listen for "eloquent.creating: *" to catch all those string events for Eloquent creating for any Model.

Event::listen('eloquent.creating: *', function ($event, $model) {
    ....
});

Obviously if you have defined your model to use custom event objects this would not be able to catch those.

You also could make a model observer, but you would have to register it to every model in your application you wanted to catch events for.

Extend the model class:

use Auth;
use Illuminate\Database\Eloquent\Model;

class GeneralModel extends Model
{
  public static function boot()
  {
    parent::boot();

    static::creating(function ($model) {
        if (Auth::user()) {
            $model->created_by = Auth::user()->id;
            $model->updated_by = Auth::user()->id;
        }
    });
  }
}

When you say create a say property object, it will be triggered. Use it for all the models you need this.

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