Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rojonunoo's avatar

Migrations foreign Key Issue

hi i keep getting this error

[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1005 Can't create table sas.#sql-8b3_67b (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table students add constraint students_grade_id_foreign foreign key (grade_id) references grades (id))

when i try to migrate on my students table

  $table->engine = 'InnoDB';

        $table->increments('id');
        $table->unsignedInteger('grade_id')->nullable();
        $table->string('name');
        $table->date('dob');
        $table->string('last_school_attended');
        $table->string('avatar')->default();
        $table->softDeletes('deleted_at');
        $table->timestamps();


        $table->foreign('grade_id')
            ->references('id')->on('grades')
            ->onDelete('cascade');

i have tried everything possible but it still gets stuck here

0 likes
6 replies
DmytroOlefyrenko's avatar

You should change

$table->unsignedInteger('grade_id')->nullable();

To

$table->unsignedInteger('grade_id')->unsigned();

Because foreign key cannot be nullable.

rojonunoo's avatar

@DmytroOlefyrenko tried that .. but still have the same issue i changed the the field to what you asked me to do i.e $table->unsignedInteger('grade_id')->unsigned();

then i php artisan migrate:rollback then did composer dump-autoload and migrated again but still had the same problem

it migrates fine but still through's up that error definitely meaning something is wrong somewhere ..:-(

rojonunoo's avatar
public function up()
{
    Schema::create('students', function (Blueprint $table) {

        $table->engine = 'InnoDB';

        $table->increments('id');
        $table->unsignedInteger('grade_id')->unsigned();
        $table->string('name');
        $table->date('dob');
        $table->string('last_school_attended');
        $table->string('avatar')->default();
        $table->softDeletes('deleted_at');
        $table->timestamps();


        $table->foreign('grade_id')
            ->references('id')->on('grades')
            ->onDelete('cascade');

    });
}

public function down()
{
    Schema::dropIfExists('students');
}

}

class CreateGradesTables extends Migration {

public function up()
{
    Schema::create('grades', function (Blueprint $table) {
        $table->increments('id');
        $table->string('grade_name');
        $table->timestamps();
    });
}


public function down()
{
    Schema::dropIfExists('grades');
}

}

@DmytroOlefyrenko

DmytroOlefyrenko's avatar
Level 8

@rojonunoo Make sure that you first run CreateGradesTables migration and then students table migration. To do it you can rename datetimes in migration file names. Because now you try create foreign key to grades table, which does not exist.

Please or to participate in this conversation.