master

laravel/framework

Last updated at: 29/12/2023 09:23

DatabaseMigrations.php

TLDR

The DatabaseMigrations trait provides methods for migrating the database before and after each test. It utilizes the Laravel framework's migration commands to refresh the test database and rollback migrations.

Methods

runDatabaseMigrations

Defines hooks to migrate the database before and after each test. It calls the beforeRefreshingDatabase, refreshTestDatabase, and afterRefreshingDatabase methods. Additionally, it registers an event to rollback migrations when the application is destroyed.

refreshTestDatabase

Refreshes a conventional test database by executing the Laravel migration command migrate:fresh with the specified migration options. It also sets the Artisan instance to null.

beforeRefreshingDatabase

Performs any work that should take place before the database has started refreshing. This method can be overridden in child classes if needed.

afterRefreshingDatabase

Performs any work that should take place once the database has finished refreshing. This method can be overridden in child classes if needed.

<?php

namespace Illuminate\Foundation\Testing;

use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\Traits\CanConfigureMigrationCommands;

trait DatabaseMigrations
{
    use CanConfigureMigrationCommands;

    /**
     * Define hooks to migrate the database before and after each test.
     *
     * @return void
     */
    public function runDatabaseMigrations()
    {
        $this->beforeRefreshingDatabase();
        $this->refreshTestDatabase();
        $this->afterRefreshingDatabase();

        $this->beforeApplicationDestroyed(function () {
            $this->artisan('migrate:rollback');

            RefreshDatabaseState::$migrated = false;
        });
    }

    /**
     * Refresh a conventional test database.
     *
     * @return void
     */
    protected function refreshTestDatabase()
    {
        $this->artisan('migrate:fresh', $this->migrateFreshUsing());

        $this->app[Kernel::class]->setArtisan(null);
    }

    /**
     * Perform any work that should take place before the database has started refreshing.
     *
     * @return void
     */
    protected function beforeRefreshingDatabase()
    {
        // ...
    }

    /**
     * Perform any work that should take place once the database has finished refreshing.
     *
     * @return void
     */
    protected function afterRefreshingDatabase()
    {
        // ...
    }
}