2

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

unclexo
  • 3,691
  • 2
  • 18
  • 26
Febri Tahta
  • 95
  • 1
  • 7

3 Answers3

4

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'); 
unclexo
  • 3,691
  • 2
  • 18
  • 26
1

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');
STA
  • 30,729
  • 8
  • 45
  • 59
1

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

Ahmad
  • 106
  • 1
  • 5