Laravel Migrations that throw an error not rollback

I found that when I created my database schema in Laravel, these failed migrations are not rolled back, making the migrations useless.

For example, I have this migration:

Schema::create('accounts', function(Blueprint $table)
{
    $table->increments('act_id');

    $table->string('act_name', 50)->unique();
    $table->boolean('act_active')->default(1);
    $table->unsignedInteger('act_type');
    $table->unsignedInteger('act_businesstype')->default(1);

    $table->timestamps();
});

Schema::table('accounts', function($table)
{
    $table->foreign('act_businesstype')->references('bst_id')->on('businesstypes');
});

      

Anyway, if I run this transfer, the table is created just fine, but the foreign key fails and I get an error. It's great. I should get an error. BUT, common sense led me to assume the following:

  • Since the migration failed, the changes should be automatically rolled back. Well, they don't.

Ok so

  1. I need to call migrate: rollback to revert these changes. Well, there is no record of the migration happening, so I end up rolling back the one that happened before.

Am I doing something wrong here? The only way I've figured out how to "undo" a failed migration is to actually go to the database and drop the table. This is very frustrating when working on a complex circuit where I am fixing bugs.

So, I guess now that I had my little bombast my question is:

How do I undo a migration that throws an error?

+3


source to share


1 answer


One solution is to perform your migrations from a transaction, so if an intermediate migration occurs when an error occurs, nothing happens and the entire transaction returns. Antonio Carlos Ribeiro wrote a great class that handles this process neatly; see his process description here , as well as the complete migration class on GitHub .

Once you've set up your class, create your migrations to extend the new migration class, and call migrateUp()

and migrateDown()

instead of up()

and down()

:



class CreateAccountsTable extends PragmaRX\Support\Migration {

    protected function migrateUp()
    ...

      

... and no need to manually fix the failed migration again!

+1


source







All Articles