Skip to content

Instantly share code, notes, and snippets.

@Braunson
Created July 23, 2021 16:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Braunson/e69b525c1ea00ea1bc1654ec4c1babbe to your computer and use it in GitHub Desktop.
Save Braunson/e69b525c1ea00ea1bc1654ec4c1babbe to your computer and use it in GitHub Desktop.
Builder macro to output raw SQL with all bindings safely encoded with support for Eloquent Builder and Query Builder.
// Support for Query Builder
Illuminate\Database\Query\Builder::macro('toRawSql', function() {
return array_reduce($this->getBindings(), function ($sql, $binding) {
$binding = str_replace(['\\', "'"], ['\\\\', "\'"], $binding);
return preg_replace('/\?/', is_numeric($binding)
? $binding
: "'" . $binding . "'", $sql, 1);
}, $this->toSql());
});
// Support for Eloquent Builder
Illuminate\Database\Eloquent\Builder::macro('toRawSql', function(){
return ($this->getQuery()->toRawSql());
});
// Usage
Model::where('foo', 'bar')->where('baz', 1)->toRawSql();
DB::table('models')->where('foo', 'bar')->where('baz', 1)->toRawSql();
// Output
select * from model where "foo" = 'bar' and "baz" = 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment