Foreign key constraint is incorrectly formed in Laravel-7 migration

135 Views Asked by At

When you are applying a foreign key using laravel migration it through this type of error

"Foreign key constraint is incorrectly formed"

The default structure of migration

User Table
---------

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });

Chat Table
---------

 Schema::create('chats', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');


        });

1

There are 1 best solutions below

2
On

This is happening because Our column size should not exactly the same size, take a look below.

$table->id();
This will create a big integer

AND

 $table->integer('user_id');
This will create a small integer that's why Our foreign key relations fails

How to Fix this issue

$table->unsignedBigInteger('user_id');

OR

$table->foreignId('user_id')->constrained();

Add unsignedBigInteger and your problem will be solved.