Laravel Advance | How to Add Foreign Key in Laravel Migration

This tutorial shows you how to add foreign keys in laravel migration. if you want to see an example of laravel migration add foreign key constraints then you are in the right place. I would like to show you the laravel migration create a table with a foreign key. you will learn to create table foreign key laravel. So, let’s follow a few steps to create an example of laravel migration create a table with a foreign key.

I will give you a very simple example of how to create a table with foreign key constraints using laravel migration. you can easily use this example with laravel 6, laravel 7, and laravel 8 versions.

in this example, we will create “posts” and “comments” table. in the comments table, we will add two foreign key constraints one with posts and another with a users table. so let’s simple create migration and let’s see:

Example 1:

Create Migration Command:

php artisan make:migration create_posts_table

database/migrations/xxxx_create_posts_table.php

<?phpuse 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

Example 2:

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

I hope it can help you…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store