DEV Community

Cover image for How to use UUID in Laravel
Husen
Husen

Posted on • Edited on

How to use UUID in Laravel

As we all know, Laravel provided Str helper to produce a UUIDv4. However, UUID is not the default primary key they use in their Eloquent. We must implement it ourselves.

In this article, I will share how use that helper to generate ID (primary key) in Eloquent automatically.

FYI, I used Laravel 6.x for this example. Maybe, you have to adjust some code, if you have different version.
I assume you have installed Laravel without a single table created.

Here are the simple steps:

  1. Change the automatic increment primary key in the table to UUID.
  2. Disable auto increment, change the table's primary key to String in Eloquent.
  3. Use helper to generate UUID in Eloquent automatically.

Change the automatic increment primary key in the table to UUID

Let's take default User model as example.

The migration above will create users table with auto increment big integer id as primary key. We can change the migration to something like this.

If your table has been filled with some data, you must change the primary key by creating a new migration. Delete the primary key, and change the id type column to UUID.

Disable auto increment, and change the table's primary key to String in Eloquent

This is default User table.

We have to override getIncrementing() and getKeyType() method from system Model.

Actually, you can override this using the property. But, I prefer to use the methode. :)

Use helper to generate UUID in Eloquent automatically

And finally, add this to boot method of the Model.

At this point, UUID will automatically be filled. But, this only applies to ordinary Model. If you have a custom Pivot model, you must change it to be like this.

Bonus

Some of you might not want to bothered with the manual method above. So, I have provided a faster way.
This is the package that I made. You can read the documentation about how to use it.

GitHub logo datakrama / eloquid

Eloquid - Auto set UUID for Eloquent Model

Top comments (1)

Collapse
 
laurence702 profile image
Francis Igbokwe

nice short article. would have been better if you at least showed some code