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.

Discussions

Author avatar
Aleksandar Mitic
3 years ago

Just what I was looking for! Thanks.

💖 1

Discussion

Get the SQL of a Query Builder without the question marks
Author avatar
Aleksandar Mitic
3 years ago

Just what I was looking for! Thanks.

💖 1
Author avatar
Loris Leiva
3 years ago

I'm glad it helped! 😊

💖 0

Would you like to chime in?

You must be a member to add a reply to a discussion.

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

Become a Member

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