Skip to content

Instantly share code, notes, and snippets.

@shawnlindstrom
Created August 13, 2021 20:02
Show Gist options
  • Save shawnlindstrom/6ec62fb0fa6f6861de9a7a899c5d2065 to your computer and use it in GitHub Desktop.
Save shawnlindstrom/6ec62fb0fa6f6861de9a7a899c5d2065 to your computer and use it in GitHub Desktop.
Laravel to SQL with Bindings Macro
<?php
namespace App\Providers;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
class MacroServiceProvider extends ServiceProvider
{
public function register()
{
/**
* Borrowed from Telescop
* @see https://github.com/laravel/telescope/blob/4.x/src/Watchers/QueryWatcher.php#L85
**/
Builder::macro('toRawSql', function() {
$sql = $this->toSql();
foreach ($this->getBindings() as $key => $binding) {
$regex = is_numeric($key)
? "/\?(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/"
: "/:{$key}(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/";
if ($binding === null) {
$binding = 'null';
} elseif (! is_int($binding) && ! is_float($binding)) {
$binding = DB::connection()->getPdo()->quote($binding);
}
$sql = preg_replace($regex, $binding, $sql, 1);
}
return $sql;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment