0

I am quiet new to laravel and bumped into this error message

( SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'landlords' (SQL: alter table `apartments` add constraint `apartments_landlord_id_foreign` foreign key (`landlord_id`) references `landlords` (`id`))).

I have changed the migration date between apartment and landlords table but the error persists as seen in the image.just below the apartment migration file is the landlords tables,the landlord's table has an earlier date to the apartments table.

here's the apartment table code

    {
        Schema::create('apartments', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->longText('description');
            $table->decimal('price');
            $table->foreignId('user_id')->constrained('users');
            $table->foreignId('landlord_id')->constrained('landlords');
            $table->timestamps();


        });
    }
``` ....dated 2021_02_16_232034_create_apartments_table


Here's the landlord's table migration file.


```    public function up()
    {
        Schema::create('landlords', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->foreignId('apartment_id')->constrained('apartments');
           $table->foreignId('user_id')->constrained('users');
            $table->timestamps();

            });

    }
```dated 2021_02_16_232129_create_landlords_table

1 Answers1

0

In your first migration (create_apartments_table) you create a constraint on a landlords table which still does not exist, thus the error.

To avoid this, you can delay creating the constraint after you have created landlords table. So in the first migration remove the constraint and in the second migration (create_landlords_table) after you've created landlords table you modify apartments table to have a constraint with landlords table.

public function up()
{
    Schema::create('landlords', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->foreignId('apartment_id')->constrained('apartments');
        $table->foreignId('user_id')->constrained('users');
        $table->timestamps();
    });

    Schema::table('apartments', function(Blueprint $table) {
        $table->foreignId('landlord_id')->constrained('landlords');
    });
}
Anurat Chapanond
  • 2,837
  • 3
  • 18
  • 31