Get the SQL of a Query Builder without the question marks
3 years ago
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
For these times where you want to copy/paste the SQL from your query builder to your database software but cannot be bothered to manually replace all them bloody question marks.