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
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
{
//..
}
来源:https://stackoverflow.com/questions/47670778/how-to-implement-eloquent-saving-event-for-all-models-not-individually