Exists some way to do some actions after a transaction fails in laravel?, I know it’s possible to use a try/catch, but inside of the transaction are other delegate instructions that alredy utilizes try/catch statement.
DB::transaction(function () {
$this->otherService->Create($data);
});
class OtherService
{
public function Create(){
try{
//Some database operations
}catch(Exception $e){
}
}
}
I need help, thanks!
2
Answers
If you want to handle failed transactions without using a
try/catch block
directly around the transaction, you can leverage database events and observers. Laravel provides aTransactionCommitted
andTransactionRolledBack
event that you can listen to and perform actions upon. This avoids placing a try/catch block directly around your transaction code.Create an observer that listens to the
TransactionRolledBack
event:Inside the
TransactionFailedObserver
class, handle the rollback event:Register the observer in the
EventServiceProvider
:Trigger the transaction without a
try/catch block
:You can do that by using Manual Transactions: