Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours scrolling social media and waste money on things we forget, but won’t spend 30 minutes a day earning certifications that can change our lives.
Master in DevOps, SRE, DevSecOps & MLOps by DevOps School!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

how to check the query execution time in Laravel

Laravel

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 2 votes
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