last query in laravel

pakainfocom profile image pakainfo ・1 min read

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.

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

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 last query in laravel:

Here is simple Debugging example.

$employees= DB::select('select * from employee where 1');
$query = DB::getQueryLog();
$lastQuery = end($query);


Array ( [query] => select * from employee where 1 [bindings] => Array ( ) [time] => 0.41 )

Posted on by:

pakainfocom profile



My name is Angular King. I'm a full-stack developer, entrepreneur and owner of Pakainfo. I live in India and I love to write


Editor guide

I do something similar in all my laravel applications.
I enable the log by default in specific environments in the AppServiceProvider::boot method

if(App::environment('local', 'testing')) {

Then I have a file with helpers where I add the last_query helper.

if(!function_exists('last_query')) {
    function last_query($connection = null) {
        $log = $connection === null ? DB::getQueryLog() : DB::connection($connection)->getQueryLog();
        if(is_array($log)) {
            $last = end($log);
            return $last;

        return false;