Take a closer look to a single sql statement in Laravel

Your application creates a lot of sql statement, but what if you want to zoom in on one single statement ?

2 minutes

Take a closer look to a single sql statement in Laravel

Showing the sql statements processed by your application ?

Most of our applications are database driven. When using Laravel you are using Eloquent and the Query Builder all the time.
These very handy built-in tools are capable of transforming your code to database queries that are executed against the database of your choice. In my case this is mostly MySql.

We often come in the situation where we have to enhance performance or troubleshoot a query. In these situations you need to take a look into the queries that are executed. Telescope is an example of a tool created by the Laravel core team that is capable of doing that. The tools of my choice are itsgoind/clockwork or barryvdh/debugbar. These tools give you a dedicated tool into your application or your developers tools that can be used without leaving your application.

All of these tools show you all the statements that are processed by your application, so if you perform 20 query in a request, all these queries will be shown. This is not always the best solution, if you are debugging something then you want to draw attention to one single part of the code, and this might be a single query.

To solve this issue I've created a composer package, I'll give you a short tour in the next chapter.

Laravel showsql

Laravel showsql is a Laravel package to output a specific sql to your favourite debugging tool, your browser or your log file.

Use case

You often want to draw the attention and look into one single sql while you are developing. You can look up your sql in your favourite debugging tool in the sql tab , but most of the time your sql is not the only sql executed ... So the searching begins. With this package you can add showSql() to your QueryBuilder and the single sql will be outputted to the logging of your debug tool.

The supported log output is Laravel Telescope, Laravel Log, Ray, Clockwork, Laravel Debugbar and your browser. By default, showSql will try to log to Ray, Clockwork or the Laravel Debugbar if one of them is installed. If all installed it will be output to all. If you want your own log implementation you can pass a callback to showSql.

If you want to change this behaviour you can publish the config file and change it.


composer require dietercoopman/laravel-showsql --dev


# With the Eloquent Builder




# With the Query Builder

DB::table('menus')->where('id', '=', 10)->showSql()->get();

DB::table('menus')->join('statuses', 'statuses.id', '=', 'menus.status_id')

# With a callback 

$callback = function(string $sql){

DB::table('products')->where('id', '=', 1)->showSql($callback)->get();

this article has been read 22 times