Created
February 1, 2022 18:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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