Observers in Laravel

Dikshant Rajput
2 min readSep 13, 2021

--

Observers are used in the case where you want to make a model to listen to multiple events at the same time and you just have to register observer once rather than events that needs to be registered everytime you create an event.

Observers as the name suggests is used to observe the application. There are many use cases of creating observers like if you want to do any fix operation on creating of that model instance or updating, deleting or restoring of a particular model instance, you don’t need to call events separately or write code in your controller everytime. You just have to create an observer and it will do the required actions in the backend.

Events provided by observers by default are :-

  • Retrieving
  • Creating
  • Updating
  • Deleting
  • Restoring
  • Force Deleting
  • Saving

Creating an observer

php artisan make:observer UserObserver --model=User

This will create an UserObserver class file in the App\Observers directory with some default methods

Registering the observer

You can register the observer in EventServiceProvider file like this:

public function boot(){
User::observe(UserObserver::class);
}

This will register the observer throughout the application itself.

The methods are called in this order:

  • Saving
  • Creating
  • Created
  • Saved

Saving method is called on every event while dealing with model and at last of every event saved method is called.

Muting the events

If you want to mute the events for a particular model instance like suppose you have to create a user from admin panel and you don’t want to perform any event then you can use this to save:

$user = User::withoutEvents(function(){
User::where('id',1)->delete();
});

If you want to change a property of a model like a user name and don’t want to call any event like updating or saving event then use this:

$user->name = 'ABC';$user->saveQuietly();

All the code for the above tutorial can be found here:

If you like the blog, don’t forget to hit the clap icon and if you want to read more such blogs, do follow me up.

--

--

Dikshant Rajput
Dikshant Rajput

Responses (1)