Created
July 23, 2021 16:31
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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