How to Add Foreign Key in Laravel Migration

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to add foreign key in Laravel migration.

 

How to add foreign key in Laravel migration

To add a foreign key constraint to a table in a Laravel migration, you can use the foreign method on the Blueprint object.

Here's an example migration that adds a foreign key constraint to a posts table, referencing the users table:

 

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

class AddUserIdToPostsTable 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');
        });
    }
}

In this example, the up method adds a new user_id column to the posts table and then creates a foreign key constraint that references the id column in the users table.

The down method drops the foreign key constraint and then drops the user_id column.

 

Note: You should ensure that the referenced column is indexed, otherwise the migration will fail.

Comments 0

Leave a comment