Get last executed query in laravel 6, 7, 8, 9, 10; In this tutorial, we are going to show you how to get last executed query in laravel 6, 7, 8, 9, 10 apps.
When developing a Laravel application, it can be helpful to retrieve the last executed query for debugging and performance analysis purposes. Laravel’s database query builder and Eloquent ORM provide methods to retrieve the last executed query. In this article, we will discuss how to get the last executed query in Laravel.
How to Get Last Executed Query in Laravel
Using the following method, you can print or get last executed query in laravel 10, 9, 8, 7, 6 apps; as following:
- Method 1: Using DB facade
- Method 2: Using Eloquent’s
toSql
method - Method 3: Using the
getQuery
method
Method 1: Using DB facade
The DB
facade provides a getQueryLog
method that returns an array of all queries executed by the application. By accessing the last element of the array, we can retrieve the last executed query.
use Illuminate\Support\Facades\DB;
$query = DB::getQueryLog();
$lastQuery = end($query);
In this code, we first retrieve the query log using the getQueryLog
method on the DB
facade. We then access the last element of the array using the end
function to retrieve the last executed query.
Method 2: Using Eloquent’s toSql
method
Eloquent’s toSql
method returns the SQL query string for the current query. By calling the toSql
method after executing a query, we can retrieve the last executed query.
use App\Models\User;
$results = User::all();
$lastQuery = $results->last()->toSql();
In this code, we execute a query to retrieve all users using Eloquent’s all
method. We then access the last element of the results using the last
method and retrieve the SQL query using the toSql
method.
Method 3: Using the getQuery
method
The getQuery
method on a query builder instance returns the Illuminate\Database\Query\Builder
instance that was used to create the query. We can use this instance to retrieve the last executed query.
use Illuminate\Support\Facades\DB;
$results = DB::table('users')->get();
$lastQuery = $results->getQuery()->toSql();
In this code, we execute a query to retrieve all users using the query builder’s get
method. We then retrieve the query instance using the getQuery
method and retrieve the SQL query using the toSql
method.
Conclusion
Retrieving the last executed query in Laravel can be done using different methods, such as accessing the query log, using Eloquent’s toSql
method, or using the getQuery
method on a query builder instance. By retrieving the last executed query, we can debug and optimize our application’s performance. It is a powerful tool to understand what is happening under the hood of our Laravel application.
Be First to Comment