-
Type: Bug
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: Laravel
florianJacques has created Issue #2851: Transaction level not working when use closure in laravel-mongodb. This Jira ticket was filed by GromNaN
Issue Text:
The transaction level remains at 0 when we use laravel automatic transactions.
```php
$connection->transaction(function () use ($connection)
);
```
Display 0.
Here's a suggested fix
```php
/**
- Static transaction function realize the with_transaction functionality provided by MongoDB.
* - @param int $attempts
*/
public function transaction(Closure $callback, $attempts = 1, array $options = []): mixed
{
$attemptsLeft = $attempts;
$callbackResult = null;
$throwable = null;
$callbackFunction = function (Session $session) use ($callback, &$attemptsLeft, &$callbackResult, &$throwable) {
$attemptsLeft--;
$this->transactions = 1;
if ($attemptsLeft < 0)
{ $session->abortTransaction(); $this->transactions = 0; return; } // Catch, store, and re-throw any exception thrown during execution
// of the callable. The last exception is re-thrown if the transaction
// was aborted because the number of callback attempts has been exceeded.
try
catch (Throwable $throwable)
{ throw $throwable; }finally
{ $this->transactions = 0; }};
with_transaction($this->getSessionOrCreate(), $callbackFunction, $options);
if ($attemptsLeft < 0 && $throwable)
{ throw $throwable; } return $callbackResult;
}
```