Laravel Custom Foreign Key Name Example

10-Apr-2023

.

Admin

Hi Guys,

Now let's see example of how to create custom foreign key name in migration laravel.you can easy and simply create custom foreign key name in migration laravel.

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

Here i will give example of products table and connected with users and categories table. So let's see the bellow example:

Create Migration


php artisan make:migration create_products_table

database/migrations/2021_06_01_130929_create_products_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

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

$table->id();

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

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

$table->string('title');

$table->text('description');

$table->decimal('price',8,2);

$table->timestamps();

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

$table->foreign('product_id', 'cm2_category_id_foreign')->references('id')->on('categories');

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('products');

}

}

Run the migration

php artisan migrate

It will help you....

#Laravel 8

#Laravel 7

#Laravel

#Laravel 6