Accidentally deleting Laravel database when running tests? Here is what to do instead

On 2024 April: updated to adapt Laravel 11


2 min read

Laravel 11

Since Laravel 11 removed `tests/CreatesApplication.php` file I had to dig up a new solution. Sadly, there isn't the perfect pretty one. I had to overwrite the refreshApplication method which comes from the BaseTestCase class.

protected function refreshApplication(): void

    // Check if the application is running unit tests
    if ($this->app->runningUnitTests() === false) {
        trigger_error('Wrong testing environment, phpunit.xml ignored');

Before Laravel 11 (original write up)

For a long time in my first years of dev journey I would accidentally wipe out the local database when I would run tests. This would because I have cached the config for unspecified reasons.

After falling into the same pit hole for enough times, I figured there's a way out.

So far every Laravel project comes with a phpunit.xml file. This file contains environment variables that are loaded when tests run. If they are not, that's how we can accidentally delete the database. If they're not, that's how we can also save ourselves.

In the tests/CreatesApplication.php file we need to check that we're in a testing environment, if not, we trigger a fatal error:


namespace Tests;

use Illuminate\Contracts\Console\Kernel;

trait CreatesApplication
     * Creates the application.
     * @return \Illuminate\Foundation\Application
    public function createApplication()
        $app = require __DIR__ . '/../bootstrap/app.php';


        if ($app->runningUnitTests() === false) {
            trigger_error('Wrong testing environment, phpunit.xml ignored');

        return $app;

Did you find this article valuable?

Support Lukas by becoming a sponsor. Any amount is appreciated!