Milind Daraniya

How To Get Last Executed Query in Laravel 10

Published August 10th, 2023 12 min read

During development or debugging in Laravel, it can be helpful to print or retrieve the last executed database query. Laravel provides a convenient method to access this information. Let's explore how you can accomplish it:

Step 1: Enable Query Logging

  • By default, Laravel's query logging is disabled. To enable it, open your .env file and set DB_QUERY_LOG=true.

Step 2: Retrieve the Last Executed Query

  • In your code, you can use the DB::getQueryLog() method to obtain the last executed query. This method returns an array containing all the executed queries.
$queryLog = DB::getQueryLog();
$lastQuery = end($queryLog);
  • In the example above, we retrieve the query log using DB::getQueryLog() and store it in the $queryLog variable. Then, we access the last executed query using end($queryLog), which returns the last element of the array.

Step 3: Print or Use the Last Query

  • You can print or access different parts of the last query, such as the SQL statement, bindings, execution time, etc., based on your needs.
$query = $lastQuery['query'];
$bindings = $lastQuery['bindings'];
$time = $lastQuery['time'];

echo "Last Query: {$query}";
echo "Bindings: " . print_r($bindings, true);
echo "Execution Time: {$time} ms";

In the example above, we assign the SQL query to the $query variable, the query bindings to the $bindings variable, and the execution time to the $time variable. You can then print or use these values as required.

Now you can easily print or retrieve the last executed query in Laravel 10 and gain insights into your application's database interactions! 📊💻