Skip to content

Instantly share code, notes, and snippets.

@aarondfrancis
Last active October 12, 2022 15:29
Show Gist options
  • Save aarondfrancis/1adee6f3cf81329dd3efa96721c54a3a to your computer and use it in GitHub Desktop.
Save aarondfrancis/1adee6f3cf81329dd3efa96721c54a3a to your computer and use it in GitHub Desktop.
<?php
Builder::macro('debug', function ($name = null) {
$name = $name ?? 'Untitled';
$sql = SqlFormatter::format($this->toBoundSql(), false);
$sql = htmlentities($sql);
$html = <<<EOT
<div>
<div class="mt-1 pl-2 w-40 py-1 bg-indigo-900">-- SQL for "$name"</div>
<div class='mb-1 text-indigo-300'>
<pre class='pl-3'>$sql;</pre>
</div>
</div>
EOT;
render($html);
});
Builder::macro('toBoundSql', function () {
$sql = $this->toSql();
$sql = str_replace('"', '', $sql);
$sql = str_replace('`', '', $sql);
$params = array_map(function ($item) {
if ($item instanceof \DateTime) {
$item = (string) $item;
}
$item = is_string($item) ? "'{$item}'" : $item;
$item = is_bool($item) ? (int) $item : $item;
return $item;
}, $this->getBindings());
return Str::replaceArray('?', $params, $sql);
});
Builder::macro('dumpBoundSql', function () {
echo $this->toBoundSql() . "\n";
});
Builder::macro('dumpBoundExplain', function () {
echo "explain " . $this->toBoundSql() . ";\n";
});
\Illuminate\Database\Eloquent\Builder::macro('toBoundSql', function () {
return $this->query->toBoundSql();
});
\Illuminate\Database\Eloquent\Builder::macro('debug', function ($name = null) {
return $this->query->debug($name);
});
\Illuminate\Database\Eloquent\Builder::macro('dumpBoundSql', function () {
return $this->query->dumpBoundSql();
});
\Illuminate\Database\Eloquent\Builder::macro('dumpBoundExplain', function () {
return $this->query->dumpBoundExplain();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment