Skip to content

Auditing with DB::beginTransaction() on PostgreSQL #1043

@evertonpavan

Description

@evertonpavan

PHP Version

8.4

Laravel Version

12.15

Package Version

14.0

Description

Root Cause

  1. Laravel Auditing attempts to create audit records during the transaction
  2. When an SQL error occurs inside the transaction, PostgreSQL enters a "failed transaction" state
  3. In this state, all subsequent commands are ignored, including the audit INSERT
  4. The audit still tries to save, generating the 25P02 error

Error Message

SQLSTATE[25P02]: In failed sql transaction: 7 ERROR: current transaction is aborted, 
commands ignored until end of transaction block
(Connection: pgsql, SQL: insert into "audits" ...)

```php
public function handle(PaymentStatusChanged $event)
{
    try {
        DB::beginTransaction();
        
        $payment->status_code = 'CONCLUIDO';
        $payment->save(); // Audit attempts to register here
        
        // If an error occurs here, the transaction fails
        $credit->addAmount($invalidAmount); // ERROR!
        
        DB::commit();
    } catch (\Exception $e) {
        DB::rollBack(); // Too late, audit already tried to save
        throw $e;
    }
}

Steps To Reproduce

public function handle(PaymentStatusChanged $event)
{
   try {
       DB::beginTransaction();
       
       $payment->status_code = 'CONCLUIDO';
       $payment->save(); // Audit attempts to register here
       
       // If an error occurs here, the transaction fails
       $credit->addAmount($invalidAmount); // ERROR!
       
       DB::commit();
   } catch (\Exception $e) {
       DB::rollBack(); // Too late, audit already tried to save
       throw $e;
   }
}

Possible Solutions

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions