Laravel

Laravel Efficient SQL Debugging: How to Display Detailed Queries with DB::enableQueryLog()

In the world of programming, especially when working with databases, interactions are an unavoidable part of an engineer’s daily tasks.
This article clearly explains how to debug SQL statements in Laravel.

Basics of SQL Debugging: How to Write a Controller to Display SQL Queries

Using the DB Class with use Declaration

First, enable the use of the DB class in PHP with a use declaration. This makes it easier to interact with the database.
Declare use DB;

use DB;

Utilizing DB::enableQueryLog()

To debug SQL queries, use DB::enableQueryLog(). Write this function before executing the query, and use DB::getQueryLog() after execution to retrieve the query result. The result can be output using the print_r function.

  1. Write “DB::enableQueryLog()” before the SQL query
  2. After executing the SQL query, write “$queryResult = DB::getQueryLog()”
  3. Output the query result “$queryResult” using “print_r($queryResult)”
DB::enableQueryLog();

$sql = DB::select("SELECT * FROM products, users WHERE …");

$queryResult = DB::getQueryLog();
print_r($queryResult);

Output SQL Results Using toSql

After executing an SQL query, you can also output the query result using $sql->toSql() with print_r.

$sql = DB::select("SELECT * FROM products, users WHERE …");

print_r($sql->toSql());

 
However, since toSql() is not available for all query types, the more versatile enableQueryLog() is recommended.

Conclusion

Interacting with databases is a fundamental skill for engineers. SQL debugging in Laravel plays an important role during the development process. By practicing the methods introduced in this article, you can quickly identify issues in your SQL queries and perform efficient debugging. If you’re a beginner engineer, take this opportunity to master SQL debugging techniques.

 
*If you reuse this content, please do so at your own discretion.