How to see SQL request Laravel

Learn how to view Laravel SQL queries with an example.

Seeing SQL Requests in Laravel

Laravel provides several ways to access and work with databases. One of the most useful is the ability to view the raw SQL queries that are being generated by Eloquent. This can be useful when trying to optimize queries or to debug why something isn't working as expected.

To view the SQL queries that are being generated by Eloquent, you can use the DB::listen() method. This method takes a Closure that will be called when a query is executed. Inside the Closure you can inspect the SQL query and any bound parameters.

DB::listen(function($query) {
    var_dump($query->sql);
    var_dump($query->bindings);
    var_dump($query->time);
});

The $query object has three properties: sql, bindings, and time. The sql property is the raw SQL query as a string, the bindings property is an array of the query's bindings, and the time property is a float representing the time it took to execute the query.

Alternatively, you can use the toSql() method to get the raw SQL of a query. This method takes no arguments and returns the SQL query as a string.

$users = AppUser::where('active', 1)->get();
$sql = $users->toSql();

var_dump($sql);
// "select * from `users` where `active` = ?

This method is useful when you want to inspect the query without actually executing it. It is also helpful when you want to debug a query that is not working as expected.

By using the DB::listen() method and the toSql() method, you can easily inspect the SQL queries that are being generated by Eloquent. This can be a great way to optimize queries and debug any issues you may be having.

Answers (0)