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:
- Change the automatic increment primary key in the table to UUID.
- Disable auto increment, change the table's primary key to String in Eloquent.
- 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
We have to override
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.
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.
Top comments (1)
nice short article. would have been better if you at least showed some code