What is Laravel Model Observers?
Observers are used to group event listeners for a model. Observers classes method names refer to the Eloquent event you want to listen for. These methods receive the model as their only argument. Laravel does not include a default directory for observers.
Eloquent models fire several events, allowing you to hook into the following points in a model’s lifecycle:
Retrieved: after a record has been retrieved.
Creating: before a record has been created.
Created: after a record has been created.
Updating: before a record is updated.
Updated: after a record has been updated.
Saving: before a record is saved (either created or updated).
Saved: after a record has been saved (either created or updated).
Deleting: before a record is deleted or soft-deleted.
Deleted: after a record has been deleted or soft-deleted.
Restoring: before a soft-deleted record is going to be restored.
Restored: after a soft-deleted record has been restored.
Why we want to use Model Observer.
Now, suppose, if we want to concatenate the string with category name, but we do not want to write the logic or function in the controller then, we can use the Model Events. It will fire automatically when the new record is created or updated or deleted. There are some types of Model Events available in Laravel Doc
Keeps the controllers lean
Using observers will allow controllers to do what they’re supposed to do. Receive requests and return responses. By using observers, you are handing more of the logic over to the model layer which is generally seen to be good practice nowadays.
Encourages maintainable code
Observers make it easier to follow the Keep it simple, stupid design principle. By abstracting some of your logic into observers, you are organising your code base and defining design standards which will be more easily understood by the developers working on the code base in the future.
Encourages reusable code
As the first example below will show, observers make for a very DRY (Don’t Repeat Yourself) codebase. By avoiding repeating yourself, you minimise bugs and localise them. Would you rather fix the same bug in many places? Or just in one place? It’s a no-brainer.
Limitations
There are some limitations attached to Model Observer which you should keep in mind while using the model observers.
When you use saved or saving hooks, you should never call the model’s save method.
If you are using saved hook and want to call the save method, then you should probably use the saving hook.
If your logic need to call model’s save method, then rethink your logic or avoid using observers.
CONCLUSION
Eloquent model observers are a very powerful and useful feature but must be used with care. They can make your codebase more maintainable but you need to be mindful of their limitations.
Top comments (0)