Tags
Asked 2 years ago
17 Jun 2021
Views 174
Stefanie

Stefanie posted

print last executed sql query with Query log in Laravel

print last executed sql query with Query log in Laravel
hanuman

hanuman
answered Apr 27 '23 00:00

In Laravel, you can print the last executed SQL query using the Query log. Here's how to do it:

First, you need to enable the Query log in Laravel. This can be done by setting the DB_LOG_QUERIES environment variable to true in your .env file :



DB_LOG_QUERIES=true

Next, you can retrieve the Query log using the DB::getQueryLog() method. This method returns an array of all the queries that have been executed since the Query log was enabled.

Finally, you can print the last executed SQL query by accessing the last element in the Query log array and getting the query key:



$queries = DB::getQueryLog();
$lastQuery = end($queries)['query'];

echo $lastQuery;
This code retrieves the Query log using DB:: getQueryLog (), gets the last element in the array using end() , and then retrieves the query key of that element.

Note that you should only use the Query log for debugging and profiling purposes, and not in production environments. It can have a performance impact on your application, especially if you have a large number of queries.
Post Answer