skip to Main Content

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.

2

Answers


  1. You could create a helper function that handles this. You can then call this helper function in your down methods.

    if (!function_exists('drop_table_with_fk')) {
        function drop_table_with_fk($table)
        {
            IlluminateSupportFacadesSchema::disableForeignKeyConstraints();
            IlluminateSupportFacadesSchema::dropIfExists($table);
            IlluminateSupportFacadesSchema::enableForeignKeyConstraints();
        }
    }
    

    Put this function in a new file in the app/Helpers directory (you might need to create this directory if it doesn’t exist). Then, you can autoload this directory by adding it to the composer.json file.

    "autoload": {
        "files": [
            "app/Helpers/your_helper_file.php"
        ]
    }
    

    After modifying the composer.json file, run composer dump-autoload to regenerate the autoload files. Now, you can use the drop_table_with_fk function in your down methods.

    public function down()
    {
        drop_table_with_fk('table');
    }
    
    Login or Signup to reply.
  2. Laravel will trigger MigrationsStarted and MigrationsEnded events during the migration process.

    You may consider implementing the following methods in EventServiceProvider:

    use IlluminateDatabaseEventsMigrationsEnded;
    use IlluminateDatabaseEventsMigrationsStarted;
    use IlluminateSupportFacadesEvent;
    use IlluminateSupportFacadesSchema;
    
    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();
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search