Home > Software design >  Cannot drop foreign key during Laravel's migration refresh
Cannot drop foreign key during Laravel's migration refresh

Time:05-05

When I try to run php artisan migrate:refresh --seed on my tables, it always get stuck on this one:

public function down()
{
    if (Schema::hasTable('leads')) {
        Schema::table('leads', function (Blueprint $table) {
            $table->dropForeign('leads_dealer_id_foreign'); //this is the line
            $table->dropIndex('leads_dealer_id_index');
            $table->dropColumn('dealer_id');
            Schema::dropIfExists('leads');
        });
    }
}

The error is: Base table or view not found: 1146 Table 'leads' doesn't exist (SQL: alter table leads drop foreign key leads_dealer_id_foreign)

I've commented the line that produces the error in the snippet above.

  1. Why would it complain about the table not existing? Even if the table doesn't exist, I've wrapped everything inside Schema::hasTable('leads') so it shouldn't even execute that line.

  2. What causes my leads table to drop early? I've looked at my other migrations and nowhere I'm dropping that table except on its own migration file.

Thanks

CodePudding user response:

You must drop the foreign keys first, then drop the table. In order to do this move Schema::dropIfExists('leads'); outside the closure:

public function down()
{
    if (Schema::hasTable('leads')) {
        Schema::table('leads', function (Blueprint $table) {
            $table->dropForeign('leads_dealer_id_foreign'); //this is the line
            $table->dropIndex('leads_dealer_id_index');
            $table->dropColumn('dealer_id');
        });
        Schema::dropIfExists('leads');
    }
}
  • Related