Log all queries in a Laravel CLI command

Mattias Geniar, Friday, March 3, 2017 - last modified: Thursday, March 9, 2017

For most web-based Laravel projects, you can use the excellent laravel-debugbar package to have an in-browser overview of all your queries being executed per page. For commands run via Artisan at the command line, you need an alternative.

This is a method I've used quite often while working on DNS Spy, since most of the application logic is inside worker jobs, executed only via the CLI.

So here's a quick method of logging all your SQL queries to the console output instead.


use Illuminate\Support\Facades\DB;

public function handle()
      \DB::listen(function($sql) {

First, import the DB Facade.

Next, add a new listener for every query being executed, and let it var_dump() the query. Alternatively, you can use dump() or dd(), too.

The result;

$ php artisan queue:work
string(170) "select * from `xxx` where `xxx`.`record_id` = ? and `xxx`.`record_id` is not null ..."
string(146) "insert into `xxx` (`value`, `nameserver_id`, `ttl`, ... ) values (?, ?, ?, ...)"

Adding a DB listener is a convenient way of seeing all your queries right at the console, for times when the debugbar can't be used!

Hi! My name is Mattias Geniar. I'm a Support Manager at Nucleus Hosting in Belgium, a general web geek & public speaker. Currently working on DNS Spy & Oh Dear!. Follow me on Twitter as @mattiasgeniar.

Share this post

Did you like this post? Will you help me share it on social media? Thanks!


Leave a Reply

Your email address will not be published. Required fields are marked *

Inbound links