Assalamualaikum & Hi,
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.
Create a new Laravel Application
laravel new observer-app
Create a directory called
app directory and create a new file called
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
Lastly, update your user’s migration file to add in new column called
php artisan migrate
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 and add the following codes to create a new user.
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 (
So, that’s how a simple user case on observe events emiited by Eloquent.
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
boot method will be bloated.
Three issues here:
- Bloated Codes
- Unmanageable Codes
- Single Observer, observe by many models.
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
Same thing I will apply for the Bloated Codes.
Create a file name
Add the following codes in
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
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:
Now update your
observes() to run both
You’re done now! Here some example on how you can setup your