Laravel News
Follow
A guide to Laravel's model events
Model events in Laravel automatically dispatch when specific actions occur on Eloquent models, eliminating the need for manual dispatching. These events can be triggered before or after an action and include events for retrieval, creation, update, deletion, and soft deletion.To listen to model events using dispatchesEvents, define a dispatchesEvents property on the model that maps Eloquent events to event classes. These event classes are dispatched automatically when the corresponding action occurs, and listeners can be created for them.Listeners are blocks of code that handle events. They are typically defined in the app/Listeners directory and contain a handle method that accepts an event instance. When an event is dispatched, its listeners' handle methods are executed.The CalculateReadTime listener calculates the reading time of a post based on word count when the PostSaving event is dispatched before saving the post.The SoftDeleteAuthorRelationships listener soft-deletes all posts related to an author when the AuthorDeleted event is dispatched before deleting the author.Model events can also be listened to using closures on the model itself. For example, the deleting event can have a closure that deletes related posts when the model is soft-deleted.While model events are convenient, it's important to use them correctly to avoid side effects.Consider using alternative approaches like using observers or extending the model class for more complex event handling scenarios.