Sorting by

×

Why I don’t use `dropIfExists` in down methods

Tips

When you use the make:migration --create=table_name command in Laravel, the generated migration will look like this:

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('table_name', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('table_name');
    }
};

In our projects, we always change that down method from dropIfExists to drop.

It’s a small thing, but there really should be no circumstance where you already ran this migration and the new table did not get created.

The one place this could happen is if the migration failed partway through. Maybe you were creating multiple tables and running other queries and it failed in the middle.

This also assumes you’re not using one of the database engines that supports transactions around schema changes.

In that case, I argue it’s better to migrate:fresh and not try to handle all possible failure and rollback scenarios in your down method.

And if you’re resistant to the idea of even having a down method, we’ve shared our thoughs on that in both audio and written form before.

Here to help,

Joel

P.S. Have you seen our book Mastering Laravel Validation Rules?

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest Comments
No comments to show.