How to get last executed query in Laravel?

In this tutorial, we explain how to get the last executed query in Laravel. We will share the best example of how to get last executed query in Laravel. This post will give you a simple example of how to print last query in Laravel.

To get the last executed query in Laravel, you can use DB facade’s logging capabilities. Laravel provides a convenient method to log and retrieve the last executed SQL query.

1. Get last executed query in laravel using toSql()

In this example, we can directly get the current SQL query using the ‘toSql()’ method of the Laravel query builder. There is no need to enable query log, you can directly query as shown example below.

 $user = User::Where('active', 1)->toSql();
 
 dd($user);
Output:
select * from `users` where `id` = ?
2. DB::enableQueryLog()
Example

In this example we must enable the query log using ‘DB::enableQueryLog()’ of the Laravel query builder. ‘enableQueryLog()’ will allow storing all executed queries in the cache, and we can retrieve those queries using ‘DB::getQueryLog()’.

DB::enableQueryLog();

$user = User::where('id', 1)->get();

$query = DB::getQueryLog();

dd($query);
3. Retrieving the last executed query
DB::enableQueryLog();

Run your database queries as you normally would. For example below.

$users = DB::table('users')->where('status', 'active')->get();

After running the query, you can retrieve the last executed query as follows:

// Get the query log
$query_log = DB::getQueryLog();

// Get the last executed query
$last_query = end($query_log);

// Print the last executed query
dd($last_query);

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *