Hello developers! In this guide, we'll learn about how to add foreign keys in laravel 10 and laravel 11 migration. Sometimes we need to establish relationships between different database tables to get records or display records.
In this step-by-step guide, I'll walk you through the process of integrating a foreign key into your database schema. Here, we'll define the products table with a comments table and add product_id into the comments table.
How to Add Foreign key in Migration in Laravel 10 and Laravel 11.
First, create a migration using the Artisan command:
php artisan make:migration create_products_table
Navigate to the newly created migration file in the database/migrations
directory and open it. Add the code for the foreign key column within the up
method.
<?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->string('name');
$table->text('description');
$table->timestamps();
});
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('product_id');
$table->text('comment');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('product_id')->references('id')->on('products');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('comments');
Schema::dropIfExists('products');
}
}
Method 2:
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->foreignId('product_id')->constrained();
$table->text('comment');
$table->timestamps();
});
Execute the migration to apply the changes to your database:
php artisan migrate
If you need to undo the migration, use the following command:
php artisan migrate:rollback
This will undo the last batch of migrations, including the foreign key column.
That's it! You've successfully added a foreign key in a Laravel 10 and Laravel 11 migration.
You might also like: