Laravel — Logging Query Events

Rudashi
Nov 7, 2020

--

When creating an API, it is sometimes necessary to know if our code is not doing any unnecessary SQL queries.

These few lines of code allow queries to be written to the /storage/logs/query.log

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Database\Events\QueryExecuted;

private function queryListener(): void
{
DB::listen(function (QueryExecuted $q) {
File::append(
storage_path('/logs/query.log'),
$q->sql.' ['.implode(', ', $q->bindings).']'.PHP_EOL
);
});
}

Just put the method in ServiceProvider (eg. AppServiceProvider) and call it in the boot() method.

--

--