UUID Foreign Keys with Cascade Delete in Laravel Migrations

📖 1 minute read

When working with UUID primary keys in Laravel, use foreignUuid() instead of manually creating UUID foreign keys. It’s cleaner and supports cascade operations out of the box.

Before (manual approach)

$table->uuid('user_id');
$table->foreign('user_id')
    ->references('id')
    ->on('users')
    ->cascadeOnDelete();

After (foreignUuid approach)

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

Even better – use foreignUuid() for polymorphic relationships:

// Old way
$table->morphs('votable'); // Creates bigInteger IDs

// UUID way
$table->uuidMorphs('votable'); // Creates UUID IDs

Why this matters

  • One line instead of three
  • Laravel auto-infers the table name from the column
  • Cascade operations are explicit and readable
  • Works seamlessly with models using HasUuids trait

Full example

Schema::create('votes', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->foreignUuid('user_id')
        ->constrained('users')
        ->cascadeOnDelete();
    $table->uuidMorphs('votable');
    $table->integer('votes'); // 1 or -1
    $table->timestamps();
});

When the user or votable model is deleted, votes are automatically cleaned up. No orphaned records.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *