Laravel MySQL Cannot insert null in nullable foreign key

1.6k Views Asked by At

I'm going crazy with this error/bug. I'm using Laravel 4.2 to develop an application in which I have a table created like this:

Schema::create('stock_items', function(Blueprint $table){
  ....
  $table->integer('color_id')->unsigned()->nullable();
  $table->integer('size_id')->unsigned()->nullable();
  ....
  $table->foreign('color_id')->references('id')->on('colors');
  $table->foreign('size_id')->references('id')->on('sizes');
});

Both columns can be null but when I insert something like this:

$stock_item->color_id = NULL;
$stock_item->size_id = NULL;

I get a MySQL Error telling me: Could not insert: Cannot add or update a child row: a foreign key constraint fails

BUT if I run the exact same query laravel logs in any MySQL client, the row gets inserted. So, what's going on??

1

There are 1 best solutions below

3
On

If everything is ok using mySQL client you should see what's the difference between your SQL statement and the Laravel's.

$queries = DB::getQueryLog();
$last_query = end($queries);

checks what Laravel executed.