Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavgel85/e17c60cd849df9aff13eb8f3f5541e90 to your computer and use it in GitHub Desktop.
Save yavgel85/e17c60cd849df9aff13eb8f3f5541e90 to your computer and use it in GitHub Desktop.
Get the SQL of a Query Builder without the question marks #laravel #queryBuilder
<?php
use Illuminate\Database\Eloquent\Builder;
Builder::macro('toSqlWithBindings', function () {
$bindings = array_map(
fn ($value) => is_numeric($value) ? $value : "'{$value}'",
$this->getBindings()
);
return Str::replaceArray('?', $bindings, $this->toSql());
});
User::where('name', 'Loris')->where('age', 26)->toSql();
// --> select * from `users` where `name` = ? and `age` = ?
User::where('name', 'Loris')->where('age', 26)->toSqlWithBindings();
// --> select * from `users` where `name` = 'Loris' and `age` = 26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment