Laravel Use UUID in Eloquent Models

Let’s find out how to set up Eloquent Models to use UUIDs are Primary Key in a MySQL database, instead of auto-incrementing integers.

I won’t go into depth about the pros and cons of UUIDs when compared to a regular auto-incrementing ID because that’s a whole another topic that usually sparks global warfare.

But yeah, what is a UUID and why would you want to use this approach?

Let’s find out!

 

What is a UUID?

UUID stands for Universal Unique Identifier.

Sometimes you’ll also hear about GUID which stands for Globally Unique Identifier, a term most often used by Microsoft fanbois.

A UUID is basically a string of generated characters based on a set of rules.

There are many variants and versions, one more complicated than the other but they ultimately serve the same purpose of uniquely identifying an entity, or in our case, a record in the database.

Why use UUIDs?

Let’s take the following example:

Your app has many RESTful endpoints that look similar to this one:

GET /users/1

As you can see, we can start getting users just by iterating the ID in the URL which can sometimes pose a security risk for some applications.

Now let’s see what the same API endpoint would look like with a UUID instead of an auto-incremented integer:

GET /users/567g7854-e89b-12k3-b456-526355441111

In this case, we completely remove the chances of iterating the ID in the URL and thus adding a layer of security.

Alright, enough with the theory, let’s get to the fun part and implement the UUID mechanism.


Create the Model and the migration

Let’s start off by generating a new Model and a migration.

We’re going to create a Tracks table where we can store our favorite songs.

Open up the terminal and let’s do

php artisan make:model Track --migration

By default, Laravel migrations include a $table->id(); column in each migration you create.

To use UUIDs we must change the id() to uuid('id')->primary();

Let’s also add other columns, just for the flavor.

I’ll add the title, artist, and album columns. The album column can be nullable because a song can be a single.

The code should look similar to this one:

Create the UUID Trait

Since we’re using Laravel, I would assume you’d be using Eloquent to interact with the database.

That’s because we’re going to make use of Eloquent’s Model Events to create the UUIDs.

Let’s go ahead and create the Trait that can be used in any Model in which we want to use UUIDs.

Inside the app folder, create a new Trait folder if you don’t have one already.

Next, create a new file called Uuid and create a trait with the same name.

We’re going to create 3 methods.

The first one is the protected static function boot() where we can hook into our Model and listen for any Eloquent events.

The second one is the public function getIncrementing() method that is used by Eloquent to know if the IDs on the table are incrementing or not.

The third one is the public function getKeyType() method that just specifies that the IDs on the table should be stored as strings.

Like I said earlier, we’re going to leverage Eloquent’s Model Events to create the UUIDs.

In this case, we’re going to use the creating event which dispatches when a new Model is saved for the first time.

We check if the Model’s primary key doesn’t have a value.

If it doesn’t have a value, we then dynamically set the primary key using the uuid() method provided by the Str Class in Laravel.

Use the UUID Trait

Now let’s get back to our Model and use the Trait.

Let’s also tell our Model that we want the table to be named ‘tracks’ and we want the ‘title’, ‘artist’, and ‘album’ columns to be fillable.

Now let’s run the migration and let’s create a new record in our database.

Open up the terminal and do

php artisan migrate

Now let’s use tinker to create a new record

php artisan tinker

And let’s create a new Track object which we then insert into the database.

I will go with the song ‘The Machine‘ from the album ‘A Mother to Scare Away the Darkness‘ by the Greek band Halocraft.

$track = new App\Models\Track(
[
'title' => 'The Machine',
'artist' => 'Halocraft',
'album' => 'A Mother to Scare Away the Darkness
]);

$track->save();

Now let’s see if our primary key is indeed a UUID.

UUID in the Track MySQL table

And it is.

Awesome!


I hope you are now a bit more familiar with how to use UUIDs in a Laravel application.

Let me know in the comments if you’re interested in a post about the advantages and disadvantages of using UUIDs and I’ll do my best to provide one.

 

 

Let me know what you think about this article through comments below, or on Twitter at @pelu_carol.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.

 

You may also like...