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

avatar

You need to check sessions table and edit the foreign id user_id :

Schema::create('sessions', function (Blueprint $table) { $table->string('id')->primary(); $table->foreignId('user_id')->nullable()->index(); $table->string('ip_address', 45)->nullable(); $table->text('user_agent')->nullable(); $table->longText('payload'); $table->integer('last_activity')->index(); });

To be like this: Schema::create('sessions', function (Blueprint $table) { $table->string('id')->primary(); $table->foreignUuid('user_id')->nullable()->index(); $table->string('ip_address', 45)->nullable(); $table->text('user_agent')->nullable(); $table->longText('payload'); $table->integer('last_activity')->index(); });

👍 1

Like our articles?

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

Recent New Courses