framework: `RefreshDatabase` + double wrapping in `DB::transaction()` breaks `$afterCommit` functionality
Laravel Version
10.23.1
PHP Version
8.2.10
Database Driver & Version
8.0.33
Description
In tests, model observer created
does not run if all condition applies:
- Test uses mysql DB connection.
- Test uses
RefreshDatabase
trait. - Using
createOrFirst()
orfirstOrCreate()
method and the method is insideDB::transaction()
.
This issue started to appear in laravel/framework 10.21. I think it was introduced in https://github.com/laravel/framework/pull/48144
Steps To Reproduce
- Clone TestDBTransaction sample project.
- Make sure to update mysql database connection in your .env file.
- Run
vendor/bin/phpunit
. Test should pass but it fails. - Try to comment the lines under Failing Test (line 27 and 30) section and uncomment a line from the Passing Tests (line 35 or 38) in
NoteObserverTest
. Test now passes.
About this issue
- Original URL
- State: closed
- Created 9 months ago
- Reactions: 4
- Comments: 19 (18 by maintainers)
@mpyw thank you. Done renaming the issue.
Hmmm… Of course, this may solve the problem, but it seems to be a temporary solution. And isn’t this destructive? Without deep consideration of various patterns, inconsistencies may occur in transaction management. I think there are many projects that take advantage of the ease of transaction nesting in Laravel, and nest transactions rather easily (like putting them in the Repository layer, but also in the UseCase layer just to be safe).
I don’t have any concrete ideas, but I think it would be better if RefreshDatabase Trait can do something about it.
@mpyw do you think #48466 fixes this issue?