In this tutorial, you will learn how to add Foreign key in laravel migration with step-by-step example.
To add a foreign key constraint in a Laravel migration, you can utilize the foreign
method provided by the Laravel Schema Builder. Here’s an example of how you can add a foreign key constraint using a migration:
Create Parent Table
Create a new migration using the make:migration
artisan command:
php artisan make:migration create_organizations_table
Now open the database/migrations/2022_04_01_040458_create_organizations_table.php and put your required column names on it.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateOrganizationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('organizations', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('organizations');
}
}
Create Child Table
Now you need to create another relational table where the parent table id organization_id is added as the
foreign key.
php artisan make:migration create_projects_table
Now open your new generated migration database/migrations/2022_04_01_040458_create_projects_table.php and put the foreign key constraint just like below:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('organization_id');
$table->string('name')->nullable();
$table->timestamps();
$table->foreign('organization_id')
->references('id')
->on('organizations')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('projects');
}
}
Run the migration using the migrate
artisan command:
php artisan migrate
This will execute the migration and add the foreign key constraint to the specified table.
That’s it! You have now added a foreign key constraint to a table in Laravel using a migration.
1 thought on “How to Add Foreign Key in Laravel Migration”