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:

  1. Test uses mysql DB connection.
  2. Test uses RefreshDatabase trait.
  3. Using createOrFirst() or firstOrCreate() method and the method is inside DB::transaction().

This issue started to appear in laravel/framework 10.21. I think it was introduced in https://github.com/laravel/framework/pull/48144

cc: @tonysm / @mpyw

Steps To Reproduce

  1. Clone TestDBTransaction sample project.
  2. Make sure to update mysql database connection in your .env file.
  3. Run vendor/bin/phpunit. Test should pass but it fails.
  4. 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)

Most upvoted comments

@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?