Current Location: Home> Latest Articles> How to Retrieve the Last Executed SQL Query in Laravel

How to Retrieve the Last Executed SQL Query in Laravel

gitbox 2025-06-27

Introduction

Laravel is a popular PHP framework widely used for web backend and API development. During development, it's common to perform various database operations such as insert, update, delete, and query. For debugging or performance analysis purposes, developers often need to check the last executed SQL statement. This article explains how to achieve that in Laravel.

Implementation Approach

To retrieve the last executed SQL query, we can use Laravel鈥檚 DB::listen() method. This allows us to capture database query events. Combined with Laravel鈥檚 logging system, we can log these SQL statements for further inspection.

Using PDO and Laravel Logging

Laravel utilizes PHP鈥檚 PDO extension under the hood to interact with databases. PDO is a database abstraction layer that supports various databases such as MySQL, PostgreSQL, and SQLite. By leveraging Laravel's logging system, we can conveniently record the SQL queries being executed.

Code Implementation

Here鈥檚 how you can use Laravel's DB facade to listen to executed SQL statements:


use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

DB::listen(function ($query) {
    Log::info($query->sql);
});

The logic behind this code is as follows:

  • Register a listener using DB::listen().
  • The callback function is triggered every time a SQL query is executed. $query->sql contains the raw SQL string.
  • Use Laravel鈥檚 logging system via Log::info() to store the query in the log file.

By default, the logged SQL statements will be saved in the storage/logs/laravel.log file.

Usage Recommendation

This method is best used in a development or debugging environment. Logging all SQL queries in a production environment may impact performance or lead to data exposure. You may want to conditionally enable this listener based on the current environment.

Conclusion

This article introduced a way to monitor and log the last executed SQL query in Laravel. This is especially helpful for debugging and optimizing database performance. With Laravel鈥檚 DB::listen method and logging system, developers can easily keep track of executed SQL queries during development.