Laravel: Observer

Eloquent models fire several events, allowing you to hook into the following points in a model’s lifecycle: retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored. Events allow you to easily execute code each time a specific model class is saved or updated in the database.

Based on events above, we can capture all the events mentioned above either by setup in model’s property called $dispatchesEventsor we can setup an observer to capture all the events above.

Here I’m going to show how to setup observer and then how you can manage your observers.

Fundamental

Create a new Laravel Application laravel new observer-app

Go into observer-app directory.

Create a directory called Observers in app directory and create a new file called OnCreatingObserver.php in app/Observers

OnCreatingObserver class will capture Eloquent event on creating a new record for a given model.

Now you need to register your model, to the OnCreatingObserver. Open up your app/Providers/AppServiceProvider.php and add the following in boot method.

Lastly, update your user’s migration file to add in new column called hashslug.

Run php artisan migrate

Tinker

I always love to run and test things using Tinker, rather than test my backend codes on front-end – web.

Now create a folder in your application tinkers and add in a new file called create_user.php.

Open up create_user.php and add the following codes to create a new user.

Now run php artisan tinker tinkers/create_user.php. You should have something like the following:

Notice that we have our hashslug inserted – but we don’t even assign the value in the tinker (create_user.php)!

So, that’s how a simple user case on observe events emiited by Eloquent.

Problem Statement

So you know, you have the an observer and it’s awesome. Easy for you. But imagine you have more than 10 models need to observe the OnCreatingObserver. It’s a tedious job to manage and your AppServiceProvider‘s boot method will be bloated.

Issues

Three issues here:

Bloated Codes

Unmanageable Codes

Single Observer, observe by many models.

Solutions

Bloated Codes, UnManageable Codes

For the issue no. 1, the strategy, which I apply to my recent works – refer to how Laravel provide us to register custom commands in their app/Console/Kernel.php.

Same thing I will apply for the Bloated Codes.

Create a file name Kernel.php in app/Observers directory.

Add the following codes in app/Observers/Kernel.php. This kernel.php it’s an endpoint for register all your observers.

Above code will register all your model-observer based on your setup in $observers property. An example of the usage on how you should register your model and observer:

Once you’re done setup your model and observer, you may replace your \App\User::observe(\App\Observers\OnCreatingObserver::class); in AppServiceProvider.php with \App\Observers\Kernel::make()-&gt;observes();

Now you observers will be much cleaner and manageable.

BUT, another issue raised – what if you have a single observer, observed by many models? It’s a tedious job to register the same observer for different models.

Single Observer, Observe By Many Models.

For the previous issue, let’s refactor a bit:

Now, to add capability to register multiple models for an observer, we going to add two things:

Add property $observedBy:

Add method observeBy():

Now update your observes() to run both observeSingle() and observeBy().

You’re done now! Here some example on how you can setup your $observeBy property: