Laravel Foreign Key

Today, I will give you an example of “How to create Foreign Key in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

laravel foreign key relationship

primary key as a foreign key using migration in laravel

What is Forign Key

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables, A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table, The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.

Foreign key in Laravel

Laravel provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let’s define a cat_id column on the subcategories table that references the id column on a categories table.

Create foreign key by Laravel migration

We have two migration files in the database directory in laravel, both of them create a different table in our database. the first migration creates a table that is for categories that have a column in the name of Id.

The second migration creates a subcategories table that has a column in the name of cat_id. Now the Id column in the categories table is referenced key and the cat_id in the subcategories table is a foreign key.

See the below example where we have a categories table and a subcategories table. A category can have many subcategories and a subcategory belongs to a category.

So, let’s follow a few steps to create an example of laravel migration create a table with a foreign key.

Generating Migration

We create a new migration file for the “categories” and “subcategories” table, In your cmd terminal hit the given below command.

php artisan make:migration create_categories_table
<?php

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

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

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}
php artisan make:migration create_subcategories_table
<?php

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

class CreateSubcategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('subcategories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('cat_id');
            $table->string('name');
            $table->timestamps();

            $table->foreign('cat_id')
            ->references('id')
            ->on('categories')
            ->onDelete('cascade');
        });
    }

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

Run Migration

php artisan migrate

Categories Table:-

primary key as a foreign key in migration

Subcategories Table:-

how to create foreign key in laravel

We successfully created a category and subcategories table with cat_id as the foreign key.

Output:-

foreign key example in laravel

After defining the migration, the next step is to define the relationship in their respective model classes.

We define (belongsTo Relationship) to get all the subcategories according to category ID.

In the Subcategory Model, add

app\Models\Subcategory

    public function SubCategoryData()
    {
    return $this->belongsTo('App\Models\Category','cat_id ');
    }

Note:- To get Relationship data

$relationdata = Categories::with('SubCategoryData')->get();

In this article, we successfully integrated “Laravel Foreign Key Example using Migration”, I hope this article will help you with your Laravel application Project.

Read Also: Rating System in Laravel.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com

Scroll to Top