Connection::whenTransactionRunsLongerThan invokes a callback when the total elapsed time of a transaction exceeds a threshold you specify.
This page is based on the Laravel Framework 13.x implementation. Make sure the Framework version you use includes this method.
Register a callback
To monitor database connections across your whole application, register the callback in theboot method of a service provider. The threshold is in milliseconds.
Connection: the database connection being monitoredTransactionCommitted|TransactionRolledBack: the event indicating whether the transaction was committed or rolled backfloat: the measured elapsed time (in milliseconds)
DB::connection('mysql'). To monitor several connections, register a callback on each Connection.
What is measured
Measurement starts when the outermost transaction begins and ends when the outermost transaction commits or rolls back.0 to 1. So even when an inner transaction runs as a savepoint, its processing time is included in the elapsed time of the outer transaction. This mechanism does not let you monitor an inner transaction with its own threshold.
The callback runs after the transaction level returns to 0. If the callback passed to DB::transaction throws an exception and the transaction rolls back, you still receive the TransactionRolledBack event and the measured time. The same events fire when you call beginTransaction / commit / rollBack manually.
Specify the threshold
The first argument ofwhenTransactionRunsLongerThan accepts the following types.
Passing milliseconds directly is usually enough. If you prefer to express the threshold in time units, you can use
CarbonInterval.
0 makes every measured transaction trigger the callback.
Distinguish it from slow SQL
Laravel also provideswhenQueryingForLongerThan, which monitors the cumulative time of the SQL executed within a single request. The two APIs measure different things.
If a transaction calls an external API or waits on locks, its elapsed time can be longer than the cumulative SQL time. Recording both makes it easier to tell whether a delay comes from the SQL itself or from other work inside the transaction.