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

Make sure you have user_id in the fillable property of your Article model.

http://laravel.com/docs/5.0/eloquent#mass-assignment


I had the same problem. I added a foreign key to a table that already existed and had data and I couldn't run the migrations because it kept failing. The solution to make the migration work was to make the foreign key nullable.

$table->integer('user_id')->nullable()->unsigned();

// then the foreign key
$table->foreign('user_id')->references('id')->on('users');

Hoping it saves someone else time in the future.


I have faced this error a couple times when running migration for existing table. The cause were any of below:

  1. the type of 'user_id' and users 'id' is different. for example when 'user_id' is INT and users 'id' is BIGINT.

  2. the column 'user_id' is not empty, you need to makeit nullable

  3. there are values in column 'user_id' that do not exist in users 'id'

Tags:

Mysql

Php

Laravel