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.

<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!



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

I respect your privacy and you won't get spam. Ever.
Just a weekly newsletter about Linux and open source.

SysCast podcast

In the SysCast podcast I talk about Linux & open source projects, interview sysadmins or developers and discuss web-related technologies. A show by and for geeks!

cron.weekly newsletter

A weekly newsletter - delivered every Sunday - for Linux sysadmins and open source users. It helps keeps you informed about open source projects, Linux guides & tutorials and the latest news.

Share this post

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

Comments

Leave a Reply

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

Inbound links