0

I started working on small project using Laravel latest version, i try to make a foreign key between two table ( Buildings and Appartmens ) but i get an error message contain :

("SQLSTATE[HY000]: General error: 1005 Can't create table `project`.`apartments` (errno: 150 "Foreign key constraint is incorrectly formed")")

this is my buildings table schema :

Schema::create('buildings', function (Blueprint $table) {
        $table->id();
        $table->string('address');
        $table->timestamps();
    });

this is my apartments table schema :

Schema::create('apartments', function (Blueprint $table) {
        $table->id();
        $table->string('number');
        $table->integer('monthly_price');
        $table->integer('rooms');
        $table->integer('bath_room');
        $table->string('description');
        // Foreign Key 
        $table->foreignId('building_id')->constrained('buildings');
        // Record Times
        $table->timestamps();
    });
  • Does this answer your question? [Laravel migration: "Foreign key constraint is incorrectly formed" (errno 150)](https://stackoverflow.com/questions/32669880/laravel-migration-foreign-key-constraint-is-incorrectly-formed-errno-150) – jewishmoses Aug 03 '20 at 15:15
  • @jewishmoses same problem :( –  Aug 03 '20 at 15:24
  • In which order are these migrations running? the buildings migration has to run before the apartments migration. – Remul Aug 03 '20 at 15:28
  • @Remul apartments runs first i think, how can i flip the order ? –  Aug 03 '20 at 15:29
  • You could rename them and change the date, or delete the apartments migration and create a new one. – Remul Aug 03 '20 at 15:31
  • 1
    @Remul, its okey i have changed the name of the migration like that i have changed the order thank you –  Aug 03 '20 at 15:32

1 Answers1

1

It looks like your apartments migration runs before your buildings migration, so no foreign key can be created because the buildings table has not yet been created.

To fix this you can change the date that prefixes the migration, for example:

2020_08_03_140214_create_apartments_table

2020_08_03_140387_create_buildings_table

to:

2020_08_03_140387_create_buildings_table

2020_08_03_140388_create_apartments_table

Don't forget to run a composer dump-autoload afterwards in order to update the class maps as well.

Remul
  • 7,874
  • 1
  • 13
  • 30