Foreign key constraint is incorrectly formed (Laravel Migration)

Viewed 372

As written in the error logs, maybe the error is caused different forms in the reference table and parent table but I still don't understand cause I'm new in programming

here table 1

<?php

Schema::create('questions', function (Blueprint $table) {
    $table->id();
    $table->string('question');
    $table->unsignedInteger('quiz_id');
    $table->timestamps();
});

here table 2

<?php

Schema::create('answers', function (Blueprint $table) {
    $table->id();
    $table->unsignedInteger('question_id');
    $table->string('answer');
    $table->boolean('is_correct');
    $table->timestamps();
});

Schema::table('answers', function (Blueprint $table){
    $table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');
});

what should I change in this code? thanks

3 Answers

As of Laravel 5.8 $table->id() is an alias of $table->bigIncrements('id') which sets the id column's data type to unsigned BIGINT under the hood.

In the answers table, you've $table->unsignedInteger('question_id'); which is equivalent to unsigned INT/INTEGER data type and that is not compatible with what $table->id() represents in the questions table. So you have to change the data type of question_id column to unsigned BIGINT in the answers table.

And to do that, you need to use Blueprint::unsignedBigInteger() method to make the question_id column's data type unsigned BIGINT as you're setting it up as a foreign key.

So use

$table->unsignedBigInteger('question_id'); 

Instead of

$table->unsignedInteger('question_id'); 

Be Careful: Laravel 5.8 Added bigInteger for foreign key ( As Defaults)

In your foreign key column do bigInteger() instead of integer().

$table->unsignedBigInteger('question_id');

$table->id(); is alias of $table->bigIncrements('id') so you should use $table->unsignedBigInteger('question_id');

Related