Laravel: Create Hashed ID for A Resource Using Observer

By | December 30, 2017

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: "hobart.cole@example.net",
     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?

Leave a Reply

Your email address will not be published. Required fields are marked *

19 − twelve =