Simple SQL query troubleshooting in Laravel 4

A quick tip for seeing a visual representation of your Eloquent/Query Builder queries in Laravel 4, mostly taken from here:

In your App:before filter in filters.php add:

if ( in_array(Config::getEnvironment(), array('local','test')) and (Input::get('sql') !== null) )
 {
 DB::listen(function($sql, $bindings, $time)
 {
 var_dump($sql);
 var_dump($bindings);
 });
 }

I’ve added the logic that first checks to make sure this can only be displayed in the local and test environments, and then if you append ‘?sql’ to the URL, you will see the raw SQL output.

There are other ways to display raw SQL in Laravel 4, including appending ‘->toSql()’ to your Eloquent statements or using a profiling package like this, but I think this is a nice, simple solution.

  • Luís Dalmolin

    There’s also an Illuminate event to listen to queries.

    Event::listen(‘illuminate.query’, function($query) {
    d($query);
    });