Skip to content

Instantly share code, notes, and snippets.

@juampi92
Created February 1, 2022 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juampi92/ff430b3c3be68aa6aa4f44cf3af0a3e4 to your computer and use it in GitHub Desktop.
Save juampi92/ff430b3c3be68aa6aa4f44cf3af0a3e4 to your computer and use it in GitHub Desktop.
Helper Database::log() to dump query logs. Useful for debugging artisan commands or migrations.
<?php
namespace App\Support;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class Database
{
public static function log(): void
{
if (!config('app.debug')) {
return;
}
DB::listen(function ($query) {
$bindings = array_map(
fn ($value) => is_numeric($value) ? $value : "'{$value}'",
$query->bindings,
);
$trace = collect(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 25))
->slice(3)
->first(fn (array $info) => empty($info['file']) || !Str::contains($info['file'], 'framework/src/Illuminate/Database/'));
$trace = $trace ? sprintf('%s:%d @%s', $trace['file'] ?? '', $trace['line'] ?? '', $trace['function']) : '';
dump([
'query' => Str::replaceArray('?', $bindings, $query->sql),
'time (s)' => $query->time,
'trace' => $trace,
]);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment