master

laravel/framework

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

LazilyRefreshDatabase.php

TLDR

This file contains a trait called LazilyRefreshDatabase that is used for refreshing the database before and after each test.

Methods

refreshDatabase

This method defines hooks to migrate the database before and after each test. It uses the baseRefreshDatabase method from the RefreshDatabase trait to perform the actual database refresh.

Classes

No classes in this file

<?php

namespace Illuminate\Foundation\Testing;

trait LazilyRefreshDatabase
{
    use RefreshDatabase {
        refreshDatabase as baseRefreshDatabase;
    }

    /**
     * Define hooks to migrate the database before and after each test.
     *
     * @return void
     */
    public function refreshDatabase()
    {
        $database = $this->app->make('db');

        $database->beforeExecuting(function () {
            if (RefreshDatabaseState::$lazilyRefreshed) {
                return;
            }

            RefreshDatabaseState::$lazilyRefreshed = true;

            $this->baseRefreshDatabase();
        });

        $this->beforeApplicationDestroyed(function () {
            RefreshDatabaseState::$lazilyRefreshed = false;
        });
    }
}