how to check the query execution time in Laravel

Posted by

Enable query logging: Open your Laravel application’s .env file and set DB_QUERY_LOG=true. This will enable query logging, allowing Laravel to record the executed queries.

Execute the query: In your code, execute the query you want to measure the execution time for. For example, let’s say you have the following query:

$users = DB::table('users')->get();

Measure the execution time: After executing the query, you can measure the execution time by using Laravel’s DB::getQueryLog() method. This method returns an array of all the executed queries and their execution time.

$queryLog = DB::getQueryLog()

Access the execution time: The execution time for the last executed query is stored in the time key within the query log array. You can access it like this:

$executionTime = $queryLog[0]['time'];

Display or log the execution time: You can then display or log the execution time as needed. For example:

echo 'Query execution time: ' . $executionTime . ' milliseconds';

Here’s the complete example:

// Enable query logging
DB::connection()->enableQueryLog();

// Execute the query
$users = DB::table('users')->get();

// Measure the execution time
$queryLog = DB::getQueryLog();
$executionTime = $queryLog[0]['time'];

// Display or log the execution time
echo 'Query execution time: ' . $executionTime . ' milliseconds';


By following these steps, you can check the query execution time in Laravel and use it to monitor and optimize your database queries.

5 1 vote
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] how to check the query execution time in Laravel […]

1
0
Would love your thoughts, please comment.x
()
x