How To Use UUIDs Instead of Numeric IDs in Laravel 5.8+

Recently I’ve decided I want to use UUIDs for a small project I’m working on behind the scenes (more coming soon). This isn’t built-in out of the box with Laravel (hopefully one day) so here’s a quick little how-to that I used to get this working.

First, you’ll want to update any migrations you have so the field is set up to support UUIDs. Luckily this is very simple!

...

Schema::create('users', function (Blueprint $table) {
            $table->uuid('id')->primary();

...

How nice and dandy!

Now, you’ll need to update your model so that it automagically just does the UUID without you having to remember it whenever calling create() and whatnot. I’ll break this down in to a few sections.

First, we’ll want to tie in to Laravel’s boot() method in our model. This will allow us to do extra extravagant things just before it tries to actually commit the model to the database. The section of code you will want to add is:

protected static function boot()
{
        
    parent::boot();

    static::creating(function ($user) {
        $user->{$user->getKeyName()} = (string) Str::uuid();
    });

 }

This tells it to generate a UUID as it is “creating” (building and saving it in the database) the model. This gets called automatically whenever we do User::create() within our code.

The next step is to tell Laravel that the primary key doesn’t increment. This is also very easy and just requires the snippet below.

public function getIncrementing()
{

    return false;

}

Then the final part is to tell it that the primary key is a string rather than an integer. Again, this is very easy to do (thanks Taylor!).

public function getKeyType()
{

    return 'string';

}

And there you have it! You can use UUIDs until your heart is content, or not, that’s really up to you. I hope you had fun!

See you next time!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.