In this tutorial you will learn about the Laravel Fix 150 “Foreign key constraint is incorrectly formed” error In Migration and its application with practical example.
Laravel “Foreign key constraint is incorrectly formed” Error
In Laravel 5.8, sometime when you generate a create table migration with a foreign key constraints, running migration may encounter 150 “Foreign key constraint is incorrectly formed” error. This is mainly happens when you take foreign key column of integer type instead of bigInteger, and this new laravel convention was causing this error. In Laravel 5.8, when you create a new table migration it will be generated with an ‘id’ column of bigInteger type instead of integer like old laravel version.
1 |
$table->bigIncrements('id'); |
Instead of (in Laravel Old versions):
1 |
$table->increments('id'); |
In that case we have to use bigInteger for foreign key column instead of an integer. So your code will look like this:
Example:-
1 2 3 4 5 6 7 8 |
Schema::create('posts', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('user_id'); $table->string('title'); $table->string('body'); $table->timestamps(); $table->foreign('user_id')->references('id')->on('users'); }); |
Or you could also use increments instead of bigIncrements for ‘id’ column in table creation of reference table.
1 |
$table->increments('id'); // ok |
instead of:
1 |
$table->bigIncrements('id'); // was the error. |
The main difference between Integer and BigInteger is of their size:
int => 32-bit
bigint => 64-bit