SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint Laravel

Apply these rules below to your migration files:

[1]

The parent, pivot table(s) must be based on engines that supports foreign key referencing (e.g InnoDB for mysql).

Do $table->engine = “InnoDB”; in your migration file, right before other column definitions.

I observe laravel always default to MyISAM hence this line is a must.

[2]

The referenced columns in the parent must be a primary or unique key(s).

These declarations in the parent table are fine:

$table->increments(“id”); means column “id” is referencable

$table->column_type(“column_name”)->unique(); means column “column_name” is referencable

[3]

The pivot table column must be of the same type as that of its referenced parent table column.

So for example, the pivot table column that should reference increments(“id”) must of type of unsignedInteger.

If parent table is type char(20), then pivot table column used to reference it must be type char(20) as well.

Having done all three above, define your foreign key relationship as appropriate.


Looks like this was not the problem for you, but I arrived at this same error in Laravel 5.8 and found an interesting issue: Laravel now defaults the 'id' column to 'bigIncrements' instead of just 'increments'. So instead of referencing it with 'integer' like before, you have to reference it with 'bigInteger'.

If your parent table looks like this:

$table->bigIncrements('id');

Then the child migration needs to look like this:

$table->bigInteger('parent_id')->unsigned()->index();
$table->foreign('parent_id')->references('id')->on('parent');

Hopefully this helps anyone else encountering this problem in 5.8 and beyond.


Quoting this answer:

To find the specific error run this:

SHOW ENGINE INNODB STATUS;

And look in the LATEST FOREIGN KEY ERROR section.

It may be a problem of type. comment_lot_id must be the exact same type as lot_id. Maybe one is signed and the other unsigned.