How to Add Foreign Key in MIGRATION using Laravel?

Spread the love

Hello Guys,

Learn How to Add Foreign Key in Migration with this Laravel Tutorial

If you’re looking to understand how to add a foreign key in migration using Laravel, you’re in the right place. In this tutorial, we’ll walk you through a practical example of adding a foreign key constraint to a migration in Laravel. We’ll show you how to create tables with foreign keys in Laravel, guiding you through each step.

We’ll provide you with a straightforward example of utilizing migration in Laravel to build a table with a foreign key constraint. This example is compatible with Laravel versions 6, 7, 8, 9, and 10.

In this illustrative example, we’ll create tables for both “posts” and “comments.” Within the comments table, we’ll add two foreign key constraints, one linking to the posts table and the other to the users table. Let’s begin by creating a migration and exploring the process:

Add foreign key in migration Example 1:

Create Migration Command:

Also Read: How to Rollback Migration in Laravel?

php artisan make:migration create_posts_table

database/migrations/2021_04_01_040458_create_posts_table.php

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('body');
            $table->timestamps();
        });
  
        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('post_id');
            $table->text('comment');
            $table->timestamps();
   
            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('post_id')->references('id')->on('posts');
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('comments');
        Schema::dropIfExists('posts');
    }
}

run migration

Also Read: How to Drop Soft Delete from Table using Migration in LARAVEL?

php artisan migrate

Example 2:

Also Read: how to Create Custom Artisan Command in LARAVEL

Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained();
    $table->foreignId('post_id')->constrained();
    $table->text('comment');
    $table->timestamps();
});

Your quest for the best Laravel blog ends here, where expert knowledge meets curated excellence.

Leave a Comment