How to create Foreign Key Constraints in Laravel

How to create Foreign Key Constraints in Laravel

In Laravel we can define relationships between two tables using the foreign key and used to link them. It refers to the primary key of the main table. The main table is called the parent table and another table which have a primary key and foreign key is called the child table. In Laravel If the foreign key's onDelete clause is defined, the database should delete the users if the user is deleted.

It will clear with below example, in which create two tables users and posts. 

First run these two commands to create a migration

php artisan make:migration create_users_table --create=users
php artisan make:migration create_posts_table --create=posts

Two migration files were created under laravelApp/database/migrations. Open these files and replace them with below code.

users table migration

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

posts table migration

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
$table->string('title')->unique();
$table->longText('content')->nullable();
$table->string('image')->nullable();
$table->unsignedBigInteger('created_by');
$table->foreign(''created_by'')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
        });
    }

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

After that run command `php artisan migrate`. Tables were created in your database `users` and `posts`. Posts table data will delete if a user row is deleted.

Hi, I'm Saurav, the developer behind usingphp. Donate to help me keep usingphp free and maintained.

Please let me know what your thoughts or comments are on this article. If you have any suggestion or found any mistake in this article then please let us know.

Latest Comments

Ruby seth
Ruby seth
20 Dec 2020

love laravel. Very simple to set foreign in 2 tables sing laravel

Ashish Bajpai
Ashish Bajpai
21 Dec 2020

Nice Post! Thanks

Add your comment