A tutorial to examine the SQL queries generated and executed by Eloquent using the Illuminate\Support\Facades\DB facade in a Laravel project.
🌍 The French version of this publication : Laravel - Analyser les requêtes SQL générées par Eloquent avec la façade DB
The PHP Laravel framework provides the Illuminate\Support\Facades\DB
class, which allows direct interaction with the database without necessarily using Eloquent (Laravel's models). However, when using Eloquent to perform queries, it can be useful to know the SQL queries that are being executed.
To retrieve the SQL query executed by Eloquent, along with the actual values used and execution time, the DB
class offers the following methods:
-
enableQueryLog()
to enable query logging -
getQueryLog()
to retrieve the query logs
Simply start by using DB::enableQueryLog()
before the query or queries you want to inspect, and then use dd(DB::getQueryLog())
to display the log. Here’s an example:
use Illuminate\Support\Facades\DB;
DB::enableQueryLog();
$users = User::with("activities")->where("email", "wilo.ahadi@hgr-adi.com")->get();
dd(DB::getQueryLog());
This source code generates an array containing the following information:
[
0 => [
"query" => "select * from `users` where `email` = ?"
"bindings" => [
0 => "wilo.ahadi@hgr-adi.com"
]
"time" => 19.88
]
1 => [
"query" => "select * from `activities` where `activities`.`user_id` in (1)"
"bindings" => []
"time" => 1.59
]
]
Therefore, we have:
-
query
: the executed SQL query. -
bindings
: the actual values used to replace the question marks (?) in the query. -
time
: the execution time of the query in milliseconds.
Take care! 😎