Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sebastiansulinski's avatar

DatabaseTransactions does not roll back after each test

I'm writing the tests where the record gets added to a table with a unique email column. I'm using DatabaseTransactions trait, but when I run the test I get:


Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'cmd@gmail.com' for key 'users_email_unique'

The beginDatabaseTransaction method of the trait seem to run the rollBack for beforeApplicationDestroyed, which would indicate that it runs from within the tearDown method before the next test, but I still get the error above. However - if I manually call:


$this->app->make('db')->rollBack();

at the end of each test - the error is gone.

Any thoughts?

0 likes
5 replies
Bloomanity's avatar

I have the same issue when I have a setUp method in my tests. But ...

/**
     * Setup the test
     */
    public function setUp()
    {
        parent::setUp();

        $this->beginDatabaseTransaction();
   }

Fixes it

1 like
bencarter78@hotmail.com's avatar

If I'm understanding you, rather than DatabaseTransactions you might want to look at DatabaseMigrations.

From the docs...

"Using Migrations

One option is to rollback the database after each test and migrate it before the next test. Laravel provides a simple DatabaseMigrations trait that will automatically handle this for you. "

1 like
nate.a.johnson's avatar

This only applies to MySQL: One thing that tripped me up once was that my table type was set to MyISAM which does not support transactions and the laravel testing trait just silently ignored that. Once I switched over to InnoDB, everything worked as I expected.

1 like
nhevan's avatar

Run the following command and you should see your tests running smoothly again.

php artisan config:clear
1 like

Please or to participate in this conversation.