DB::whenQueryingForLongerThan()
Get notified when your cumulative database query time exceeds a threshold during a single request.
Overview
This method fires a callback when the total time spent querying the database in a single request exceeds a given threshold. Unlike slow query logs that flag individual queries, this catches death by a thousand cuts — many fast queries adding up.
Usage
Register this in your AppServiceProvider:
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Connection;
public function boot(): void
{
DB::whenQueryingForLongerThan(500, function (Connection $connection) {
logger()->warning(
"Database queries exceeded 500ms on [{$connection->getName()}]."
);
});
}
The threshold is in milliseconds. The callback receives the connection instance that exceeded the threshold.
When to Use
- Detecting request-level performance regressions in production
- Alerting when a page accumulates too many queries (even if each one is fast)
- Pairing with
Model::preventLazyLoading()for comprehensive query monitoring