Is there a way to disable foreign key constraints when any "down" function triggers?

56 Views Asked by At

I'm discussing an efficient approach to execute the Schema::disableForeignKeyConstraints() whenever an artisan migrate:refresh command is executed. For instance, we can integrate it into the migration file within the down() method. Here's an example:

public function down()
{
    Schema::disableForeignKeyConstraints(); // Disable foreign key constraints
    Schema::dropIfExists('table'); // Delete the table
    Schema::enableForeignKeyConstraints(); // Re-enable foreign key constraints
}

Is there an event designed for table drops that we can leverage by invoking it in the AppServiceProvider? This would be a more streamlined solution than adding these two lines to each migration file.

1

There are 1 best solutions below

0
yasiao On BEST ANSWER

Laravel will trigger MigrationsStarted and MigrationsEnded events during the migration process.

You may consider implementing the following methods in EventServiceProvider:

use Illuminate\Database\Events\MigrationsEnded;
use Illuminate\Database\Events\MigrationsStarted;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Schema;

public function boot()
{
    // Listen for the event that migrations are starting.
    Event::listen(MigrationsStarted::class, function () {
        Schema::disableForeignKeyConstraints();
    });

    // Listen for the event that migrations have ended.
    Event::listen(MigrationsEnded::class, function () {
        Schema::enableForeignKeyConstraints();
    });
}