Skip to content

Instantly share code, notes, and snippets.

@arodbits
Last active January 20, 2020 09:55
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save arodbits/c061d56dc620284ab22526294b43518a to your computer and use it in GitHub Desktop.
Save arodbits/c061d56dc620284ab22526294b43518a to your computer and use it in GitHub Desktop.
Combine binding values into a raw SQL query in Laravel. Debugging in Laravel.
<?php
//example:
$query = Foo::where('id', '=', 1)->where('name', '=', 'bar');
//would produce the following raw query:
//select * from foo where id = ? and name = ?;
dd(vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function($binding){
return is_numeric($binding) ? $binding : "'{$binding}'";
})->toArray()));
//result:
//select * from foo where id = 1 and name = 'bar';
@havietduc91
Copy link

Thank @thonyx, it's saved my time a lot!

@andreshg112
Copy link

Thanks! It also worked for me!

@brayandemarchi
Copy link

works for me too, thanks bro!!

@spaceemotion
Copy link

Thanks a lot! Here's a version without using the Laravel Collection:

return vsprintf(str_replace('?', '%s', $query->toSql()), array_map(function($binding) {
    return is_numeric($binding) ? $binding : "'{$binding}'";
}, $query->getBindings()));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment