📖 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
HasUuidstrait
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.
Leave a Reply