Laravel 13 has a lot of improvement features. In these features, I would like to emphasize one by one on each feature. In this post, I would like to address the Model Events.
What is Model Events?
A model event is when the eloquent is executed something. For example, The event created is triggered when the user is created in an eloquent model. That is a lot easier to manage, commit and rollback. For example, when a user is created, there is an email verification have to be sent, the user created functionality will handle the verification email sending to the user. When there is a user required to be removed, the remove trigger will process some extra jobs.
How Model Events works before Laravel 13?
Before Laravel 13, We need to create Model observers. There will be a total of 3 files, or may be even more. That will include the controller, the Model and the observer, plus the Application service provider for linking these files.
When the controller is executed, the Model is loaded and executed, then the application service provider will call the Model Observer to handle the execution task before and after the model is executed.
That makes the magic. Many of the developers will not have such understanding of the model execution and the aftermath is working. It will make them confused on what is actually happening. This is stated by many devs and youtube videos about the magic. The entry point is less visible and accessible then the normal paths.
Laravel 13, Event Closure
In Laravel 13, the event closure will handle within the model class. That will make the developer to handle the post and pre works inside the Model. That has two advantages: visibility and single responsibility.
According to the handling methods of earlier models, the system have to handle a lot of task at once and there will be file refactoring and extension for the single responsibility. In this update the single responsibility is much more easier and the visibility will get higher.