makapaka's avatar

Anyone have a function to combine sql bindings for outputting

I am using the DB::listen() with $query->sql and $query->bindings to show every query in my logs. I would like to auto combine the bindings so that what I output is the full query without having to manually do it - before I take the time to write something I was wondering if anyone already has something they could share :)

0 likes
7 replies
Borisu's avatar

You could actually use this instead:

DB::enableQueryLog();
// do queries
DB::getQueryLog();

This will start tracking the queries and then output them with the bindings and all. From here you can put some logic in your AppServiceProvider to log the result of DB::getQueryLog()

1 like
staudenmeir's avatar

You want to replace the ? placeholders with the bindings?

$sql = Str::replaceArray('?', $query->bindings, $query->sql);
1 like
makapaka's avatar

@staudenmeir this is the kind of thing I was after but I cant seem to find any documentation on Str::replace - is this php or laravel specific ?

Borisu's avatar

@makapaka Just a side note, you could use the Debugbar package or Telescope. Both will show you detailed information about your queries with bindings. Just something to consider before you go digging in the logs :)

CaptainHypertext's avatar

Came across this while trying to do the same thing. I'm using named parameters so the given answers didn't work for me, but I found a stupidly simple way to do it, assuming your bindings are in an associative array:

str_replace(array_keys($bindings), array_values($bindings), $query_string);

Please or to participate in this conversation.