Setup UUID as Primary Key in Laravel 7

In case you never heard about Laravel, you can visit here.

Photo by Christopher Gower on Unsplash

Default primary key for Laravel Model is using increment integer, for reference. In some case, developer want to use another type such as UUID. What is UUID? In short, UUID stands for Universally Unique IDentifier, for more explanation, please read also here.

You only need some steps to change your Model so use UUID as default.

  1. Create Uuid Trait, for example I place the file in App\Traits with name Uuid.php. In this example, we use id column as our primary key, you can use another column as your want.

Notes: In case you want to know what is trait, read here.

2. Change your Model, for example we change User class. Here the change

3. Change your migrations files, because we use users, here the example changes.

Hopefully this will help you.

For another Models that use same column, you can reuse the Uuid trait and do some change same with step 2 and 3.

Backend Developer — Focus at Microservices and Cloud Computing

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store