Identifying and Logging Duplicate Queries in Laravel Requests
When developing your Laravel application, you want to avoid unnecessarily making duplicate requests for performance reasons. However, it can be challenging to identify how many and which queries are duplicates. Here's a helper script that logs duplicate queries to the laravel.log
file and records how many times they were executed.
Place this code in the boot()
method of your AppServiceProvider.php
file, then check your laravel.log
file. This code uses Redis, but you can swap it to Cache.
Redis::del('QueryStats');
Event::listen(QueryExecuted::class, function (QueryExecuted $event) {
Redis::rpush('QueryStats', json_encode([
'connection' => $event->connectionName,
'query' => $event->sql,
'bindings' => $event->bindings,
'time' => $event->time,
'trace' => collect(debug_backtrace())->map(function ($trace) {
return Arr::only($trace, ['file', 'line', 'class', 'method']);
})->toArray(),
]));
});
$this->app->terminating(function () {
$stats = Redis::lrange('QueryStats', 0, -1);
$data = [
'query_count' => 0,
];
foreach ($stats as $stat) {
$queryStat = json_decode($stat);
if (str_contains($queryStat->query, 'telescope_')) {
continue;
}
if (!isset($data[$queryStat->query])) {
$data[$queryStat->query] = 1;
} else {
$data[$queryStat->query] += 1;
}
$data['query_count'] += 1;
arsort($data);
}
Log::info($data);
});