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

寵の児 提交于 2020-01-23 20:48:32

问题


Based on documentation of laravel eloquent event, all the eloquent event are triggered individually based on each model, is there any way to use 'creating' event or any other eloquent event to be triggered by all the Models

For example , if any Models is created , event A is triggered


回答1:


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.




回答2:


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
{
  //..
}


来源:https://stackoverflow.com/questions/47670778/how-to-implement-eloquent-saving-event-for-all-models-not-individually

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