0
0
LaravelHow-ToBeginner · 4 min read

How to Create Foreign Key in Migration in Laravel

In Laravel migrations, create a foreign key by using $table->foreign('column')->references('id')->on('other_table'). This links the column to the primary key of another table, enforcing relational integrity.
📐

Syntax

Use the Laravel schema builder to define a foreign key in a migration. The syntax has three parts:

  • $table->foreign('column'): specifies the column that will hold the foreign key.
  • ->references('id'): points to the column in the other table that this key references, usually the primary key.
  • ->on('other_table'): names the table that contains the referenced column.
php
Schema::table('table_name', function (Blueprint $table) {
    $table->foreign('column_name')->references('id')->on('other_table');
});
💻

Example

This example shows how to add a foreign key user_id in the posts table that references the id column in the users table.

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
            $table->dropColumn('user_id');
        });
    }
};
Output
When you run this migration, the posts table will have a user_id column linked as a foreign key to users.id, enforcing that each post belongs to a valid user.
⚠️

Common Pitfalls

Common mistakes when creating foreign keys in Laravel migrations include:

  • Not creating the referenced column with the correct type (usually unsignedBigInteger for id columns).
  • Forgetting to add the foreign key constraint after adding the column.
  • Trying to create a foreign key before the referenced table exists.
  • Not dropping foreign keys properly in the down() method, which can cause errors when rolling back.
php
<?php
// Wrong: missing unsignedBigInteger for foreign key column
Schema::table('posts', function (Blueprint $table) {
    $table->integer('user_id'); // should be unsignedBigInteger
    $table->foreign('user_id')->references('id')->on('users');
});

// Right:
Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users');
});
📊

Quick Reference

MethodDescription
$table->unsignedBigInteger('column')Creates an unsigned big integer column for foreign key
$table->foreign('column')Starts defining a foreign key on the column
->references('id')Specifies the referenced column in the other table
->on('table')Specifies the referenced table
$table->dropForeign(['column'])Drops the foreign key constraint
$table->dropColumn('column')Drops the column

Key Takeaways

Always define the foreign key column with the correct unsigned type matching the referenced column.
Use $table->foreign()->references()->on() to create foreign key constraints in migrations.
Ensure the referenced table exists before adding foreign keys to avoid migration errors.
Drop foreign keys explicitly in the down() method to allow smooth rollbacks.
Foreign keys help maintain data integrity by linking related tables.