ItSolutionStuff.com

Laravel Migration Custom Foreign Key Name Example

By Hardik Savani β€’ April 16, 2024
Laravel

Hi All,

In this example, i will show you laravel migration custom foreign key name. it's simple example of laravel custom foreign key name. This post will give you simple example of migration custom foreign key name laravel. let’s discuss about how to add custom foreign key name in laravel.

I will give you very simple example of how to add custom foreign key name in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.

few days ago, i added one post, how to add foreign key using laravel migration. in this post i will help you how to add custom foreign key using migration. let's see bellow example.

Create Migration Command:

php artisan make:migration create_comments_table

database/migrations/2021_04_07_125911_create_comments_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateCommentsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

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

$table->id();

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

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

$table->text('comment');

$table->timestamps();

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

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

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('comments');

}

}

by default it will take "comments_user_id_foreign" and "comments_post_id_foreign" foreign key name, but if you want to change your own then foreign function take another argument for custom name so i just rename it like "cm2_user_id_foreign" and "cm2_post_id_foreign". let's run seeder and see mysql layout.

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 Call Model Function from Another Model in Codeigniter?

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 β†’