skip to Main Content

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


  1. 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 a TransactionCommitted and TransactionRolledBack 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:

    php artisan make:observer TransactionFailedObserver --queued
    

    Inside the TransactionFailedObserver class, handle the rollback event:

    use IlluminateDatabaseEventsTransactionRolledBack;
    
    class TransactionFailedObserver
    {
        public function __construct()
        {
            //
        }
    
        public function failed(TransactionRolledBack $event)
        {
            // Logic to execute when a transaction fails
            // You can add your desired actions here, such as logging or additional operations
            
            // Example: Log the exception
            logger()->error('Transaction failed: ' . $event->exception->getMessage());
            
            // Example: Rollback another related action
            // Your code here...
        }
    }
    

    Register the observer in the EventServiceProvider:

    protected $listen = [
        'IlluminateDatabaseEventsTransactionRolledBack' => [
            'AppObserversTransactionFailedObserver@failed',
        ],
    ];
    

    Trigger the transaction without a try/catch block:

    use IlluminateSupportFacadesDB;
    
    DB::transaction(function () use ($data) {
        $this->otherService->create($data);
    });
    
    Login or Signup to reply.
  2. You can do that by using Manual Transactions:

    class OtherService
    {
        public function create($data)
        {
            try {
                DB::beginTransaction();
    
                // Some database operations
    
                // If everything is successful, commit the transaction
                DB::commit();
            } catch (Throwable $e) {
                // Something went wrong, rollback the transaction
                DB::rollBack();
    
                // Handle the exception or log it
                // You can also rethrow the exception if needed
                throw $e;
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search