Laravel migration - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Laravel migration - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails laravel laravel

Laravel migration - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails


I had the same problem. Fixed it by adding nullable to field:

Schema::create('table_name', function (Blueprint $table) {    ...    $table->integer('some_id')->unsigned()->nullable();    $table->foreign('some_id')->references('id')->on('other_table');    ...});

Note that after migration all existed rows will have some_id = NULL.

UPD:

Since Laravel 7 there is more short way to do the same thing:

$table->foreignId('some_id')->nullable()->constrained();

It is also very important that nullable goes BEFORE constrained.

More info you can find here, in official documentation


You probably have some records in the inventories table with local_id that does not have corresponding id in the contents table, hence the error. You could solve it by one of the two ways:

  • Run the migration with foreign_key_checks turned off. This will disabled the foreign key constraints for the existing rows (if that's what you want). It's documented here
  • Insert only those records that have corresponding id field in contents table. You can use INSERT INTO.. WHERE EXISTS query to filter the records out, and insert only those records.