Some time ago, I wanted a debugging tool that could present full, easy to read, copy/pastable SQL. At the time I was using it to expose N+1 lazy-loads that were hurting performance. So I actually dissected DebugBar to figure out how they managed it, and came up with something that sounds like it'd suit your purposes as well.
This basically just reformats what Laravel catches in the query log. (Of course they actually have to finish executing to be visible here.) Just make sure, if you're using any of the raw
methods, to encapsulated field names in back-ticks, or the capitalization will look a little screwy.
DB::enableQueryLog();
DB::flushQueryLog();
//Execute whatever code results in SQL queries
$queries = DB::getQueryLog();
DB::disableQueryLog();
DB::flushQueryLog();
$dbName = null;
$compiled = [];
foreach ($queries as $query) {
if (DB::getDatabaseName() != $useDb) {
$dbName = DB::getDatabaseName();
$compiled[] = "USE `$dbName`;";
}
$sql = $query['query'];
$values = $query['bindings'];
$enclosures = [
'back_tick' => '`',
'apostrophe' => "'"
];
$matches = [];
foreach ($enclosures as $name => $enclosure) {
$matches[$name] = [];
preg_match_all("/$enclosure.*?$enclosure/", $sql, $matches[$name]);
$matches[$name] = array_last($matches[$name]);
$sql = preg_replace("/$enclosure.*?$enclosure/", "$enclosure?$enclosure", $sql);
}
$sql = strtoupper($sql);
foreach ($enclosures as $name => $enclosure) {
$sql = str_replace_array("$enclosure?$enclosure", $matches[$name], $sql);
}
$values = array_map(function ($value) {
if (!is_numeric($value) && !is_null($value)) {
$value = DB::connection()->getPdo()->quote($value);
}
return $value;
}, $values);
$sql = str_replace_array('?', $values, $sql);
$sql = rtrim($sql, ';').';';
$compiled[] = $sql;
}
By the way, the DB::getQueryLog()
also includes the time it takes for a query to run, making it even more useful for diagnosing performance issues. Just bear in mind there, connection-time is a factor. Locally hosting your app that's remoting into a database will take longer to come back than when your project is actually live.