support@codebucket.net

How to add Foreign key in Laravel Migration

How to add Foreign key in Laravel Migration

K. M. Shawkat Zamil | January 12, 2023

Hello Developers,

 

A foreign key is a column or group of columns in a relational database table that links data in two tables. We can say that A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another. (You can also use a non-primary field but not recommended). 

 

Here we will create a table named requisitions and addresses. We will set the PRIMARY KEY in the addresses table as an FOREIGN KEY of the requisitions table. We will follow the steps below:

 

Install Laravel Project In Your Environment

 

First, you need to go to your development workspace. My workspace is situated in D:/ drive. Open a command prompt and write the below code to install Laravel.

 

laravel new example-app

 

Database Configuration

 

After installing the project, open the project in your code editor. Now we have to configure the database credentials. As I am using the wamp server, I have to start the server and open the localhost/phpmyadmin. In there I will create a database named example-app.

 

 

After that, add the credentials to the project .env file

 

/.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example-app
DB_USERNAME=[USERNAME]
DB_PASSWORD=[PASSWORD]

 

We will run the php artisan migrate In the command prompt run the below command:

 

php artisan migrate

 

Sometimes you might get the below error:

 

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes

 

 If you  get the error, simply add the following line in the /app/Providers/AppServiceProvider.php

 

/app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);
}

 

As your table has already been generated. Now run the php artisan migrate:fresh.

 

Create Models and Migrations

 

Our main table is requisitions. To make the migration and the model, run the below command:

 

php artisan make:model Requisition -m

 

Our model is created named 2023_01_10_102552_create_requisitions_table.php. The table has name and phone columns. The primary key is id by default. Let's define the table structure in the up() method:

 

/database/migrations/2023_01_10_102552_create_requisitions_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRequisitionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('requisitions', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('phone')->nullable();   
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('requisitions');
    }
}

 

The second table is named addresses. Initially, run the below command to create the model and migration:

 

php artisan make:model Address -m

 

Our model is created named 2023_01_12_033840_create_addresses_table.php. The table has location and address columns. The primary key is id by default. Let's define the table structure in the up() method:

 

/database/migrations/2023_01_10_102552_create_requisitions_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAddressesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('addresses', function (Blueprint $table) {
            $table->id();
            $table->string('location')->nullable();
            $table->string('city')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('addresses');
    }
}

 

Make Foreign Key in the table

 

Now make the foreign key requisition_id in the addresses table. Add the below line in the addresses table structure:

 

$table->foreign('requisition_id')->references('id')->on('requisitions')->onDelete('cascade');

 

Let's see the definitions of the functions:

  • foreign() – Pass field name which you want to foreign key constraint.

  • references() – Pass linking table field name.

  • on() – Linking table name.

  • onDelete(‘cascade’) – Enable deletion of attached data.

 

/database/migrations/2023_01_10_102552_create_requisitions_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAddressesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('addresses', function (Blueprint $table) {
            $table->id();
            $table->string('location')->nullable();
            $table->string('city')->nullable();
            $table->foreign('requisition_id')->references('id')->on('requisitions')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('addresses');
    }
}

 

As we complete the migration configurations, run the php artisan migrate to make the table in the database.

 

php artisan migrate

 

That's it for today. Hope this might help you in the journey of development.

 

Read More: Implement Remember Me in Laravel with Cookie

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.