How To Use UUIDs Instead of Numeric IDs in Laravel 7

There are many reasons you may wish to use a UUID instead of a numerical ID in your Laravel 7 project, and in this post I will document the process for doing so.

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();

...

Once this is done, you’ll need to update your model so that it automagically just applies a UUID without you having to remember it whenever calling create() or save() 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!

A next step may be to turn this in to trait so you can easily reuse it in the future. One thing to mention though is that you can only override boot() once so make sure you are careful if you do go down this route.

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.