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(AppUser::class, 10)->create();
$user = $users->first();

You should get something like:

=> AppUser {#766
     name: "Lauren McKenzie",
     email: "[email protected]",
     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 *

16 − seven =