Laravel — Logging Query Events

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store