Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

wrsandre's avatar

Log all queries to database

Hello everyone.

I'm having an issue here, I'm not being able to log queries besides selects to the database. I've tried toSql() which doesn't work with anything else but selects, and DB::getQueryLog() which retrieves an array, and I need the query as a string. Can anyone give me a little hand in here?

Thank you.

P.S: I'm on lumen 5.6.4

0 likes
7 replies
wrsandre's avatar

Thanks for the answer Sergiu, so I have been trying to use the piece of code you provided, and read the page you linked, but I am not understanding how that works. Can you please try to explain it to me?

Cronix's avatar

For every query run, it will give you the raw sql (with placeholders), the bindings used (that fill the placeholders) and how long it took the query to run. So, you can log that data however you want.

DB::listen(function ($query) {
     \Log::info($query->sql, ['Bindings' => $query->bindings, 'Time' => $query->time]);
});
1 like
wrsandre's avatar

Thanks for you answer Cronix, I got it to log to the log file. Now I wonder, is there any way for me to pass thast $query back to my controller? Because I have to log it to database with other info that I cannot access on the AppServiceProvider (that was where I wrote this DB::listen)

Cronix's avatar
Cronix
Best Answer
Level 67

Not easily. What's wrong with DB::getQueryLog()? Yes it returns an array, but it has the same data (query/bindings/time) that DB::listen() gives you and you can run it in the controller. You can manually build up a "string" containing all 3 just like when logging it, except it's an array instead of an object.

wrsandre's avatar

I was using DB::getQueryLog() but was told to change it... Guess I'll have to use it then. Thanks for your help Cronix.

Cronix's avatar

It's a lot easier to target the specific queries you're looking for. You enable the query log, do your queries, disable the log and you have what you're wanting without having to scan all queries being run.

1 like

Please or to participate in this conversation.