laravellaravel-5eloquentlaravel-events

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


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


Solution

  • 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.