Laravel Users Table: Change Primary Key ID to UUID - in 3 Steps

Want to change the default Laravel User model to use UUID instead of the default auto-increment ID? Here are the changes you need to make.


Step 1. Migration for users.

The main migration for the users table: change ->id() to uuid('id')->primary().

database/migrations/2014_10_12_000000_create_users_table.php:

Schema::create('users', function (Blueprint $table) {
$table->id();
$table->uuid('id')->primary();

Two things to notice:

  • The default ->uuid() would create a field uuid, so if you want to stick to the id, you need to specify it.
  • Also, default uuid() doesn't make that field a primary key, so you need to specify ->primary().

Step 2. Other Migrations to users.

All the migrations with foreign keys to the users table should change to foreignUuid().

$table->foreignId('user_id')->constrained();
$table->foreignUuid('user_id')->constrained();

Also, polymorphic relations for the default personal_access_tokens table:

Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->morphs('tokenable');
$table->uuidMorphs('tokenable');

Step 3. User Model: Add Trait

Finally, add a trait HasUuids to the User model.

app/Models/User.php:

use Illuminate\Database\Eloquent\Concerns\HasUuids;
 
class User extends Model
{
use HasUuids;

This will auto-generate UUIDs for every new User record.

This HasUuids feature appeared in the Laravel 9.30 version. Here's my video about it.

And that's it. Every new User would get a UUID automatically, like "8f8e8478-9035-4d23-b9a7-62f4d2612ce5".


I've performed a similar refactoring in my latest course about Travel API: watch this video (UUIDs are at the end, from 19:07)

Or, watch/read the full 2-hour course, creating a project from a real job interview task: Laravel Travel Agency API From Scratch

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 79 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials