Laravel: test if your database migrations files contain a down-method

Published 11 January 2022 08:56 (2-minute read)

Here is a quick tip on how to test if your database migrations do not contain any down methods.

I've always filled my migrations with a `down` method in my projects. But since I saw this tweet from Aaron Francis, I stopped using this in my projects.

One of our internal rules is that we only ever migrate the database forward, never backwards. It ensures a more predictable state for our database.

Here is the test you can use in your projects:

<?php

use Illuminate\Database\Migrations\Migrator;
use Tests\TestCase;

class NoDownMigrationsTest extends TestCase
{
  /** @test */
  public function there_are_no_down_migrations()
  {
    /** @var Migrator $migrator */
    $migrator = app('migrator');

    $files = $migrator->getMigrationFiles([
      $this->app->databasePath() . DIRECTORY_SEPARATOR . 'migrations'
    ]);

    $migrator->requireFiles($files);

    foreach($files as $file) {
      $class = $migrator->resolve($migrator->getMigrationName($file));
      $reflector = new ReflectionClass($class);

      // We don't use down migrations because we don't want to ever run 
      // `down` in prod, it's too dangerous. If anything from an old
      // migration needs to be undone, create a new migration for it.
      $this->assertFalse(
        $reflector->hasMethod('down'),
        get_class($class) . ' migration has a down method. Please remove it.'
      );
    }
  }
}

Thanks Aaron for this quick tip!

Robin Dirksen

Follow me on Twitter, there I post web-related content, tips/tricks, and other interesting things.

On my blog, you can find articles that I've found useful or wanted to share with anyone else.

If you want to know more about this article or just want to talk to me, don't hesitate to reach out.