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.
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 in the comments section below.
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.