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:
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
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.
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.
As the first example below will show, observers make for a very DRY (Don’t Repeat Yourself) codebase. By avoiding repeating yourself, you minimize bugs and localise them. Would you rather fix the same bug in many places? Or just in one place? It’s a no-brainer.
There are some limitations attached to Model Observer which you should keep in mind while using the model observers.
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.
Visit our next blog to show “How to install and Use Model Observers?”