Skip to content

Instantly share code, notes, and snippets.

@jampack
Forked from developerdino/DebugServiceProvider.php
Created October 17, 2019 17:00
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 jampack/a52eca91ddb55bdebcc62dd499617f56 to your computer and use it in GitHub Desktop.
Save jampack/a52eca91ddb55bdebcc62dd499617f56 to your computer and use it in GitHub Desktop.
Laravel: Log all queries with bound parameters observer.
<?php
namespace App\Providers;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
class DebugServiceProvider extends ServiceProvider
{
public function register()
{
Event::listen(
QueryExecuted::class,
function (QueryExecuted $query) {
// Format binding data for sql insertion
foreach ($query->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$query->bindings[ $i ] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$query->bindings[ $i ] = "'$binding'";
}
}
}
// Insert bindings into query
$boundSql = str_replace(['%', '?'], ['%%', '%s'], $query->sql);
$boundSql = vsprintf($boundSql, $query->bindings);
Log::debug(
"TIME - {$query->time}ms\n" .
" UNBOUND QUERY: {$query->sql};\n" .
" BOUND QUERY: $boundSql;"
);
}
);
}
}
<?php
Event::listen('illuminate.query', function($query, $bindings, $time, $name)
{
$data = compact('bindings', 'time', 'name');
// Format binding data for sql insertion
foreach ($bindings as $i => $binding)
{
if ($binding instanceof \DateTime)
{
$bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
}
else if (is_string($binding))
{
$bindings[$i] = "'$binding'";
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $query);
$query = vsprintf($query, $bindings);
Log::debug($query . ";");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment