Laravel Programming-Work with Observers to Control instead of Model



Observers are a great tool to keep the controllers neat and clean in laravel. It helps scaling and maintaining the Application in future, a lot easier!

In this example, I want to generate slug for each blog based on it’s title. However I don’t want to do something like $blog->slug = str_slug(‘$blog->title’);

If you are listening for many events on a given model, you may use observers to group all of your listeners into a single class. Observers classes have method names which reflect the Eloquent events you wish to listen for. Each of these methods receives the model as their only argument. Laravel does not include a default directory for observers, so you may create any directory you like to house your observer classes:

To Create a new folder inside App directory called Observers and there create UserActionsObserver.php