Nasrul Hazim Bin Mohamad

Laravel: Create Hashed ID for A Resource Using Observer

Dec
30

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 *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

20 + seventeen =