DEV Community

Jansen Felipe
Jansen Felipe

Posted on

[Laravel Query Monitor] - How to see queries executed by Eloquent?

This question I asked myself when I was studying the Laravel Framework. At the time, I was impressed with all the “magic” of Eloquent.

    <?php

    $users = User::where('name', "Jansen Felipe")->get();
   
    // The above code executes the following SQL statement:
    // select * from `users` where name = "Jansen Felipe"

The Eloquent included in Laravel provides a beautiful and simple ActiveRecord implementation for working with your database.
* Laravel Framework documentation *

I am in complete agreement. Eloquent is a hand in the wheel and speeds up the development of that MVP that you have to publish Friday (lol).

It turns out that, in the case of success, it is quite possible that your database will grow and your system will start to slow down. (a “good” problem, right?)

In all the slowness cases I've worked on, most were related to performance in the database. And how to see the queries executed, once they are encapsulated in the framework? It has several forms. I quote some of them:

  • One way is to access the MySQL server (for example) and run the “show processlist” command.

  • Another way is to debug the application by calling the “toSql ()” method

  • Another way is using the package https://github.com/supliu/laravel-query-monitor

Laravel Query Monitor

This package was created as a developer support tool. Through the terminal, you execute the command php artisan laravel-query-monitor and from then on, all queries executed in your application will appear in real time in the terminal.

Alt Text

To develop the package, we used React PHP to open the query listening service on the terminal. Queries are sent using the DB :: listen method as specified in the Laravel documentation https://laravel.com/docs/7.x/database#listening-for-query-events

If you want to use the package, just install it using the composer:

    $ composer require --dev supliu/laravel-query-monitor

    $ php artisan vendor:publish --provider="Supliu\LaravelQueryMonitor\ServiceProvider"

The package code is open and published under the MIT license. So, feel free to copy, use and enhance! Follow the link to the repository on GitHub https://github.com/supliu/laravel-query-monitor

Doubts, criticisms or suggestions? Feel free in the comments!

** This article was originally published in Portuguese https: //supliu.com.br/2020/04/29/laravel-query-monitor-como-ver-queries-e-executadas-pelo-eloquent/

Latest comments (0)