How to add foreign key in Laravel 9 migration?

In this tutorial, I will give you an example of “How to add foreign key in Laravel 9 migration”, So you can easily apply it with your laravel 7, laravel 8, and laravel 9, application.

First, what we’re doing here, This is the example :

foreign key in laravel 9 migration

add foreign key in laravel 9 migration

Best way to add foreign key in Laravel 9 Migration

Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let’s define a cat_id column on the posts table that references the id column on a categories table.

Categories Table

<?php

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

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

Post Table

<?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('post_title');
            $table->longText('post_content');
            $table->foreignId('cat_id')->constrained('categories')->onUpdate('cascade')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Output:-

laravel migration best way to add foreign key
create foreign key in laravel 9 migration

In this article, we learned “a foreign key concept in Laravel 9 migration”, I hope this article will help you with your Laravel application Project.

Read also:- How to use groupBy on Foreach in Blade file in Laravel.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com

Scroll to Top