How to drop foreign key during Laravel’s migration refresh?

Many times during application development in Laravel, we might need to remove a database column that has a foreign key relationship. It can be a bit tedious to perform this task. But, the migration refresh feature by the Laravel Framework makes it easy to drop foreign key constraint on another table.

The process cannot be directly performed using the dropColumn() function of a migration file. Since a foreign key contraints is applied, so we mist first drop the foreign key constraint of that column using the dropForeign() function. Then delete the column using the dropColumn() function. Let us consider the example below to better understand the use of migration to remove a foreign key attribute.

To delete a table, you first need to confirm the table details as described in the if loop shown below. However, the foreign key attribute can create problem in deletion. Therefore you should first remove the foreign key.

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 code below shows how we can use the migration refresh feature to help remove the constraint and then the database table column itself.

Schema::table('leads', function (Blueprint $table) {
    $table->dropForeign('leads_dealer_id_foreign');
    $table->dropColumn('leads_dealer_id_index');
});

However, sometimes, even using the migration refresh method you might not be able to remove the constraint. In this case you can use the dropIndex() method as specified below to drop the foreign key at the specified index.

$table->dropIndex(['state']); // Drops index 'geo_state_index'