Skip to content

Commit 9190754

Browse files
Add database afterRollback callback support and tests (#57180)
* Add database afterRollback callback support and tests * Update ManagesTransactions.php * Update DB.php * Update DatabaseTransactionsTest.php --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent 5b61771 commit 9190754

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

src/Illuminate/Database/Concerns/ManagesTransactions.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,4 +353,21 @@ public function afterCommit($callback)
353353

354354
throw new RuntimeException('Transactions Manager has not been set.');
355355
}
356+
357+
/**
358+
* Execute the callback after a transaction rolls back.
359+
*
360+
* @param callable $callback
361+
* @return void
362+
*
363+
* @throws \RuntimeException
364+
*/
365+
public function afterRollBack($callback)
366+
{
367+
if ($this->transactionsManager) {
368+
return $this->transactionsManager->addCallbackForRollback($callback);
369+
}
370+
371+
throw new RuntimeException('Transactions Manager has not been set.');
372+
}
356373
}

src/Illuminate/Support/Facades/DB.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@
114114
* @method static void rollBack(int|null $toLevel = null)
115115
* @method static int transactionLevel()
116116
* @method static void afterCommit(callable $callback)
117+
* @method static void afterRollBack(callable $callback)
117118
*
118119
* @see \Illuminate\Database\DatabaseManager
119120
*/

tests/Integration/Database/DatabaseTransactionsTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,31 @@ public function testTransactionsDoNotAffectDifferentConnections()
105105
$this->assertTrue($secondObject->ran);
106106
$this->assertFalse($thirdObject->ran);
107107
}
108+
109+
public function testAfterRollbackCallbacksAreExecuted()
110+
{
111+
$afterCommitRan = false;
112+
$afterRollbackRan = false;
113+
114+
try {
115+
DB::transaction(function () use (&$afterCommitRan, &$afterRollbackRan) {
116+
DB::afterCommit(function () use (&$afterCommitRan) {
117+
$afterCommitRan = true;
118+
});
119+
120+
DB::afterRollBack(function () use (&$afterRollbackRan) {
121+
$afterRollbackRan = true;
122+
});
123+
124+
throw new \RuntimeException('rollback');
125+
});
126+
} catch (\RuntimeException) {
127+
// Ignore the expected rollback exception.
128+
}
129+
130+
$this->assertFalse($afterCommitRan);
131+
$this->assertTrue($afterRollbackRan);
132+
}
108133
}
109134

110135
class TestObjectForTransactions

0 commit comments

Comments
 (0)