Ways to View SQL Queries in Laravel

- Andrés Cruz

En español

This material is part of my complete course and book; You can purchase them from the books and/or courses section, Curso y libro Laravel 11 con Tailwind Vue 3, introducción a Jetstream Livewire e Inerta desde cero - 2024.

In this entry, I bring you several ways in which you can see the SQL queries made per request, when we create an app in Laravel, many requests can be made by us or internally by Laravel, as we have great freedom when creating our requests , it is very likely that we make mistakes in some parts and make poorly optimized queries and the first step to correct these problems is to see the query.

Method 1: Laravel Built-in Logging System

Using the DB::listen method you can listen to the database query events and do whatever you want with this, such as recording the queries in a log or viewing them on the screen.

use Illuminate\Support\Facades\DB;

public function boot()
{
    DB::listen(function ($query) {
        \Log::info($query->sql, ['bindings' => $query->bindings, 'time' => $query->time]);
    });
}

Or on the routes:

routes/web.php

DB::listen(function ($query){
    echo $query->sql;
  //  Log::info($query->sql, ['bindings' => $query->bindings, 'time' => $query->time]);
});

Method 2: Laravel Debugbar Package

Laravel Debugbar is a tool par excellence for debugging the app, it gives us a lot of information about what is happening and among them, the SQL queries, it also gives us the execution time:

composer require barryvdh/laravel-debugbar

Method 3: Using Laravel Telescope

Laravel Telescope is the official Laravel team for debugging and monitoring, it is the previous package, but with vitamins:

composer require laravel/telescope

Then, run the Telescope installation and migration command:

php artisan telescope:install
php artisan migrate

Method 4: Using the toSql Method

The toSql method converts the Eloquent query into SQL text so that we can see how Laravel internally translates a query into SQL and be able to analyze it. It is ideal for debugging:

$sql = DB::table('posts')->where('posted', true)->toSql();

Method 5: Using the DB::getQueryLog Method

Another scheme is to use the DB::getQueryLog to get all the SQL queries executed during the current request. For example:

DB::enableQueryLog();
$queries = DB::getQueryLog();

This will return an array with all the SQL queries executed.

These are just some ways you can implement in your code to see the SQL of the queries made.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.