Skip to content

Conversation

@lucasferro0
Copy link

@lucasferro0 lucasferro0 commented Dec 8, 2025

Overview

This pull request adds automatic database transaction control during HTTP tests when the DatabaseTransactions trait is used. The implementation ensures that the transaction level is always reset to 1 after each HTTP request in the tests, preventing issues with uncommitted nested transactions. This makes the test scenario more aligned with a real-world scenario where the transaction is rolled back when a "response" is returned.

Before Changes

api.php

Route::post('users', function () {
    DB::beginTransaction();  // Starts nested transaction (level 2)
    
    User::create(['name' => 'John']);
    
    // Forgot to commit or rollback!
    return response()->json(['success' => true]);
});

UserTest.php

class UserTest extends TestCase
{
    use DatabaseTransactions;

    public function test_create_user()
    {
        $response = $this->postJson('/api/users');
        
        // Problem: transaction is still at level 2
        $this->assertDatabaseMissing('users', ['name' => 'John']); // Fails
    }
}

After Changes

api.php

Route::post('users', function () {
    DB::beginTransaction();  // Starts nested transaction (level 2)
    
    User::create(['name' => 'John']);
    
    // Forgot to commit or rollback!
    return response()->json(['success' => true]);
});

UserTest.php

class UserTest extends TestCase
{
    use DatabaseTransactions;

    public function test_create_user_without_commit()
    {
        $response = $this->postJson('/api/users');
        
        // Transaction reset to level 1 automatically
        // Nested transaction rollback was executed
        $this->assertDatabaseMissing('users', ['name' => 'John']); // Passes
    }
}

Reference links

PHP documentation - PDO Transactions

@github-actions
Copy link

github-actions bot commented Dec 8, 2025

Thanks for submitting a PR!

Note that draft PR's are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface.

Pull requests that are abandoned in draft may be closed due to inactivity.

@lucasferro0 lucasferro0 marked this pull request as ready for review December 9, 2025 00:09
@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants