Get the SQL of a Query Builder without the question marks

3 months ago
use Illuminate\Database\Eloquent\Builder;

Builder::macro('toSqlWithBindings', function () {
    $bindings = array_map(
        fn ($value) => is_numeric($value) ? $value : "'{$value}'",

    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.


Would you like to chime in?

You must be a member to start a new discussion.

Fortunately, it only takes two click to become one. See you on the other side! 🌸

Become a Member