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

fatihict's avatar

Database transactions are not working

Hello,

I have just created a new Laravel app to test my issue with DatabaseTransactions. I only edited the .env file to point to a new database i created and added a simple test. When i create a new object in my test using the ModelFactory and test the id of the newly created object, it doesn't match 1. I do use the DatabaseTransactions trait, so i expect the id of the object to be 1 every time i run phpunit. I am using Ubuntu 14.04, PHPUnit 4.8.23 and Mysql 5.7.11. Below is the code of the test class i've edited.

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    use DatabaseTransactions;
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $user = factory(App\User::class)->create();
        $this->assertEquals(1, $user->id);
    }
}

0 likes
4 replies
bobbybouwmann's avatar

Just to be sure, did you try to run php artisan migrate:refresh --database=connection first before you ran the test? This was you start with a clean database.

You can also try to do this with another database driver, sqlite for example ;)

1 like
fatihict's avatar

@bobbybouwmann Thanks for your comment Bobby. I failed to mention that i did migrate my database. I tested it with sqlite after you've mentioned it and it does work with a sqlite database. However, I do want database transactions to work with a mysql database, because i use a mysql database in production.

bobbybouwmann's avatar

Which table engine do you use? You should be able to rollback your transaction as the table engine is InnoDB.

1 like
TKay's avatar

I have tried running phpunit. Testcases refresh the database using RefreshDatabase trait. In that case it shows driver not found. For testing I have used sqlite database in environment.

  $ ./vendor/bin/phpunit
  PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20160303/php_pdo_sqlite.dll' - /usr/lib/php/20160303/php_pdo_sqlite.dll: cannot open shared object file: No such file or directory in Unknown on line 0

Please or to participate in this conversation.