(errno: 150 "Foreign key constraint is incorrectly formed") in larevl 8 code example

Example 1: errno: 150 foreign key constraint is incorrectly formed laravel 8

Since increments() creates an unsigned integer column, you need to define the foreign key column as unsigned integer too.

Default migrations in Laravel 6+ use bigIncrements(), so you need to use unsignedBigInteger() method:

$table->unsignedBigInteger('order_id');
https://laravel.com/docs/6.x/migrations#foreign-key-constraints

For default migrations in older versions of Laravel use unsignedInteger() method:

$table->unsignedInteger('order_id');
Or:

$table->integer('order_id')->unsigned();

Example 2: (errno: 150 "foreign key constraint is incorrectly formed")

I ran into this same problem with HeidiSQL. The error you receive is very cryptic. My problem ended up being that the foreign key column and the referencing column were not of the same type or length.

The foreign key column was SMALLINT(5) UNSIGNED and the referenced column was INT(10) UNSIGNED. Once I made them both the same exact type, the foreign key creation worked perfectly.

Tags:

Misc Example