Nasrul Hazim Bin Mohamad

Laravel: Observer Setup Enhancement



It’s been awhile since my last blog post. Today, just want to share something simple, an enhancement of LARAVEL: CREATE HASHED ID FOR A RESOURCE USING OBSERVER. Going to refactor a bit.

First, let’s modify the app/Observers/Kernel.php, to be like the following:

Next, add new config file for our observer – config/observers.php:

And that’s it!

Very simple and straightforward setup of Laravel Observer, much cleaner than before.

Should I make this as a package? Do let me know if you guys need this as a package. 🙂


Laravel: Create Hashed ID for A Resource Using Observer


Install hashids/hashsids package

composer require hashids/hashids

Create a wrapper for hashids

Create a helper for hashids

Create a config file for hashids

Create a migration, which add a hashslug field

Create a helper to get slug name of the given class name (optional)

Create an observer for hashids which monitor on creating new record – if there’s a hashslug column and it’s null, do create hashed id for the record.

Register the observer to model in boot() method in your app/Providers/AppServiceProvider.php

Now let’s test.

php artisan migrate
php artisan tinker
$users = factory(\App\User::class, 10)->create();
$user = $users->first();

You should get something like:

=> App\User {#766
     name: "Lauren McKenzie",
     email: "",
     hashslug: "BgJRlGpQKejb",
     updated_at: "2017-12-29 16:45:43",
     created_at: "2017-12-29 16:45:43",
     id: 1,

Notice the hashslug created in random string (hashed id).

I always use this approach to for my important resources – just to make sure people don’t get easily guess what’s my next record in database.

Happy coding!

P/S: You may encounter an issue – where a lot of models, using the same observer. How do you manage them? Keep it bloated in service provider?

Laravel: Observer


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

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


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:

Create user via tinker

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.


Three issues here:

  1. Bloated Codes
  2. Unmanageable Codes
  3. 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 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()->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:

Final Kernel File for Observer

Observer App