How to Add Foreign Key in Laravel Migration?

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

This tutorial shows you how to add foreign key in laravel migration. if you want to see lesson of laravel migration add foreign key constraint then you are a right place. i would like to show you laravel migration create table with foreign key. you will learn create table foreign key laravel. So, let's follow few step to create lesson of laravel migration create table with foreign key.

I will give you very simple lesson of how to create table with foreign key constraint using laravel migration. you can easily use this lesson with laravel 6, laravel 7 and laravel 8 version.

in this lesson we will create "posts" and "comments" table. in comments table we will add two foreign key constraint one with posts and another with users table. so let's simple create migration and let's see:

Lesson 1:

Create Migration Command:

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

php artisan migrate

Result:-

Lesson 2:

Schema::create('comments', function (Blueprint $table) {

$table->id();

$table->foreignId('user_id')->constrained();

$table->foreignId('post_id')->constrained();

$table->text('comment');

$table->timestamps();

});

thank you very much for following up with me.

Recent Posts

Related Posts