DEV Community

xnamelname
xnamelname

Posted on

How to Get Last Executed Query in Laravel?

We have been many time need to get executed query log or you want to get last executed query or maybe if you want to diaplsy sql query from laravel query builder then you can do it that. so i have three example for display executed query in Laravel 5. when you are working on laravel application at that times , i think you need many time to print last run query or if you want to check direct from phpmyadmin sql box, so at that time you have to follow this three example. so, let's see three example of getting sql query from Laravel Query Builder.

Example 1:

In this example we can get directly get current sql query using toSql() of laravel query builder. In this example you don't need to enable query log or something you can directly query like bellow example:

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

Example 2:

Ok, In this example we must need to enable query log using DB::enableQueryLog() of Laravel Query builder. enableQueryLog() will give access to store all execute query in cache and we can get that query using DB::getQueryLog(). In this example you will get all query log not last only. bellow example how to use it together.

DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
print_r($query);

Example 3:

In this example i make the same as example 2, but you can get exactly last query using end(). so let's see how to use.

DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
$query = end($query);
print_r($query);

By default query log is disabled in Laravel 5, so don't forget to enable it before getting query log.

Example 4:

public function querylog()
    {
        \DB::enableQueryLog();
        $list = \DB::table("categories")->get();
        $query = \DB::getQueryLog();
        print_r(end($query));
    }

output

  Array ( [query] => select * from `categories` [bindings] => Array ( ) [time] => 8.09 )

Example 5: Echo Last Executed Query In Laravel

To See last Executed query in Laravel 5 we need to enable query log of laravel.To Enable query log use "DB::enableQueryLog()" function before query. As we know DB::getQueryLog() function of laravel return all executed queries.To get last query we will use end() function which return last executed query.

$query = DB::getQueryLog();
$lastQuery = end($query);

Before getting query log you need to first enable it by using DB::enableQueryLog() function and then you can get all executed queries.

DB::enableQueryLog();
$users= DB::select('select * from user where 1');
$query = DB::getQueryLog();
$lastQuery = end($query);
print_r($lastQuery);

output

Array ( [query] => select * from user where 1 [bindings] => Array ( ) [time] => 0.39 )

Ref Source : last query in laravel

It will help you...

Top comments (0)