ItSolutionStuff.com

Laravel Add Foreign Key to Existing Table with Data Example

By Hardik Savani • April 16, 2024
Laravel

Now, let's see tutorial of laravel add foreign key to existing table with data. This tutorial will give you simple example of how to add foreign key in existing table in laravel. if you want to see example of laravel migration add foreign key to existing table data then you are a right place. We will look at example of laravel migration alter table add foreign key.

I will give you very simple example of how to alert table with add foreign key using laravel migration. you can easily use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.

yesterday i added one post, how to add foreign key using laravel migration. in this post i will help you how to add foreign key on existing table with data. let's see bellow example.

first you need to install doctrine/dbal composer package for alter table:

composer require doctrine/dbal

Create Migration Command:

php artisan make:migration add_foreign_key_table

database/migrations/2021_04_01_103500_add_foreign_key_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class AddForeignKeyTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

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

$table->bigInteger('user_id')->unsigned()->change();

$table->bigInteger('post_id')->unsigned()->change();

$table->foreign('user_id')->references('id')->on('users');

$table->foreign('post_id')->references('id')->on('posts');

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

}

}

run migration

php artisan migrate

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Add Foreign Key in Laravel Migration?

Read Now →

Laravel Migration - How to Add New Column in Existing Table ?

Read Now →

How to Change Table Name using Laravel Migration?

Read Now →

How to Remove Column from Table in Laravel Migration?

Read Now →

How to Change Column Name and Data Type in Laravel Migration?

Read Now →

How to Create Table using Migration in Laravel?

Read Now →

How to disable model timestamps in Laravel?

Read Now →

How to Get Table Name from Model in Laravel?

Read Now →

How to Drop Foreign Key Constraint in Laravel Migration?

Read Now →

How to Add MySQL Trigger from Migration in Laravel?

Read Now →