Introduction
As explained in the Laravel documentation, there are many fairly granular events dispatched over the model lifecycle. Most of them come in "before" and "after" variations. For example, the creating event will fire before the model is persisted to storage (usually the database), and the created event happens after it is persisted. There are countless reasons one might care about these events, such as creating some kind of notification when a certain type of model is created.
In my case, I have a model attribute that may be directly supplied by a user but will otherwise be calculated from related data. Adding a handler for the saving event will ensure that this attribute is always appropriately set before the model is written to the database. I will briefly review the options the documentation describes, explain why none of them felt appropriate for my needs, and show the options not directly explained in the documentation on model events.
The needs for your particular case will of course vary greatly, but for me, there are two key aspects of what I needed to accomplish:
- I knew I was only going to care about a single-model event.
- The entirety of my handler would only be a few lines of code.
Custom Event Classes and Observers
The first event handling option described in the documentation is to create your own custom events and map them to the model events via the model's $dispatchesEvents property. In addition to creating the custom events and mapping them, you must write a listener for each event that handles it. This is very powerful and granular when you need it. I'd even say that for applications with complex event functionality, it's arguably the "right" way to do it too.
The documentation also describes a somewhat simpler approach of creating an observer for the model, which is a class specifically for handling the model's events. This is probably a good solution if you need to handle several events, but each event's handling code is not complex enough to warrant the custom event option. While simpler than the custom events, this approach still requires that the observer is registered as the handler for the model in the application's App\Provider\EventServiceProvider class.
Because my needs were so simple, I felt it was excessive to create a separate class for a few lines of code or have to register it somewhere else, so I looked for an even simpler alternative.