Ad

Errno: 150 "Foreign Key Constraint Is Incorrectly Formed In Migration Laravel 6

- 1 answer

I'm new in laravel and sorry if my English is bad. I have made migrations file and run it

  1. create_colleges_table.php

public function up() {

 Schema::create('colleges', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->char('nim', 10);
        $table->string('email');
        $table->integer('major_id');
        $table->timestamps();
    });
}
  1. create_majors_table.php

public function up() {

Schema::create('majors', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('major_name');
        $table->timestamps();
    });
}

And then i make update_colleges_table.php, run it and getting error like this :

Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table `learn_laravel_crud`.`#sql-1558_e3` (errno:
150 "Foreign key constraint is incorrectly formed") (SQL: alter table `colleges` add constraint `colleges_major_id_foreign` foreign key (`major_id`) references `majors` (`id`))

this my code in update_colleges_table.php

public function up()

{
    Schema::table('colleges', function (Blueprint $table){
        $table->foreign('major_id')->references('id')->on('majors');
    });

}
Ad

Answer

To create Foreign key the data type for the child column must match the parent column exactly.

Since majors.id is a bigIncrements i.e unsigned big integer then colleges.major_id also needs to be an bigInteger, not a integer.

So change

 $table->integer('major_id');

to

$table->unsignedBigInteger('major_id');
Ad
source: stackoverflow.com
Ad