To check query execution time in Laravel, you can follow these steps:
- Enable Query Logging:
Laravel provides a query logging feature that allows you to log all executed queries. To enable query logging, open the.env
file in the root directory of your Laravel project and set theAPP_DEBUG
variable totrue
:
APP_DEBUG=true
This setting will enable detailed logging, including query execution time.
- Access Query Log:
Laravel stores the executed queries in a log file. To access the query log, you need to add a few lines of code to your application. Open the fileapp/Providers/AppServiceProvider.php
and import the necessary classes at the top:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
Then, inside the boot
method, add the following code to log the queries:
DB::listen(function ($query) {
Log::info('Query executed: '.$query->sql);
Log::info('Time taken: '.$query->time.'ms');
});
The DB::listen
method registers a listener that logs each executed query along with the time taken to execute it.
- Viewing the Query Log:
By default, Laravel logs all query-related information in thestorage/logs/laravel.log
file. You can view the log by using thetail
command in your terminal:
tail -f storage/logs/laravel.log
This command will display the log in real-time, allowing you to see the executed queries along with their execution time.
- Log Formatting (optional):
If you want to format the query log differently or store it in a separate log file, you can configure it in theconfig/logging.php
file. Open the file and modify the'channels'
array to include a new channel for your query log:
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single', 'query'],
],
'query' => [
'driver' => 'daily',
'path' => storage_path('logs/query.log'),
'level' => 'debug',
],
// ...
],
This configuration adds a new channel called 'query'
that writes logs to storage/logs/query.log
with a 'debug'
level.
- Analyzing Query Execution Time:
Once the query log is enabled, you can execute the desired code or requests in your Laravel application. The executed queries, along with their execution time, will be logged. You can analyze the log to identify slow or inefficient queries.
By following these steps, you can easily check the query execution time in Laravel and identify any performance bottlenecks in your application.
All the best nerd!
See our previous post here.