Introduction
When executing SQL using Eloquent ORM or Query Builder in Laravel, it is often necessary to verify what SQL is actually being run. This is useful not only for debugging but also for performance tuning.
In this article, we introduce several methods to check the executed SQL in Laravel.
1. Using the toSql() Method
The toSql()
method allows you to check the SQL statement generated by Eloquent or Query Builder. However, it does not display binding values.
$query = User::where('id', 1);
// Display SQL
$sql = $query->toSql();
echo $sql;
// Output
// SELECT * FROM `users` WHERE `id` = ?
2. Using the DB::listen() Method
The DB::listen()
method allows you to capture the executed SQL, binding values, and execution time.
\DB::listen(function ($query) {
\Log::info($query->sql);
\Log::info($query->bindings);
\Log::info($query->time);
});
To check the logs, look at storage/logs/laravel.log
.
3. Using DB::enableQueryLog()
If you want to retrieve multiple executed SQL logs at once, you can use DB::enableQueryLog()
.
\DB::enableQueryLog();
// Execute some queries
$users = User::where('email', 'example@example.com')->get();
// Retrieve executed SQL logs
$queries = \DB::getQueryLog();
dd($queries);
4. Using $query->dd() / $query->dump()
The shortest way to display the SQL statement for an Eloquent query is by using dd()
or dump()
.
$query = User::where('id', 1);
$query->dd(); // Outputs SQL and stops script execution
$query->dump(); // Outputs SQL without stopping execution
Summary
There are various methods to check executed SQL in Laravel.
Method | Features |
---|---|
toSql() | Displays SQL statement. Does not show binding values. |
DB::listen() | Logs actual executed SQL and execution time. |
DB::enableQueryLog() | Retrieves multiple executed SQL logs at once. |
$query->dd() | Displays SQL statement and stops script execution. |
Choose the most suitable method according to your needs.
コメント