Step-by-Step: Adding Foreign Keys in Laravel Migrations

 How to add foreign key in table using migration in Laravel

Create table with foreign key using migration

In this article we will see how to add foreign key on your table while creating using migration in Laravel

Table - 1 : student 

public function up()
    {
        Schema::create('student', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('address');
            $table->string('phone');
            $table->string('about')->nullable();
            $table->timestamps();
        });
    }

Table - 2 : section 

public function up()
    {
        Schema::create('section', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('student_id')->unsigned()->index()->nullable();
            $table->foreign('student_id')->references('id')->on('student')->onDelete('cascade');
            $table->string('section')->nullable();
            $table->string('stream')->nulable();
            $table->timestamps();
        });
    }

Now simply run your migration command as shown below .

php artisan migrate

Table Structure :

Create table with foreign key using migration

Create table with foreign key using migration



This is how you  can add foreign key to your table . if you want yo know how to add column , drop column and change column property click on this link .



Previous Post Next Post

Contact Form