Log all queries in a Laravel CLI command

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, March 03, 2017

Follow me on Twitter as @mattiasgeniar

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.

<?php

use Illuminate\Support\Facades\DB;

public function handle()
{
      \DB::listen(function($sql) {
          var_dump($sql->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!



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.