Laravel How to Get Last Executed Query

Published on Apr 27, 2022

Hello artisans, today I'll talk about how to get the last executed query log. This will also help us to see which raw SQL query is being performed. We'll also print the executed query through our Eloquent or any type of query being executed. We'll see 3 types of examples in our today's article.

Example 1

First we'll see the below toSql() method.

public function example1()
    {
        $query = User::select("*")->toSql();

        dd($query);
    }

It'll produce the below output

^ "select * from `users`"

Example 2

Now we'll use the enableQueryLog() and getQueryLog() method of DB class. Like below

public function example2()
    {
        DB::enableQueryLog();

        $users = User::select("*")->get();
        $quries = DB::getQueryLog();

        dd($quries);
    }

It'll produce the output in an nested array.

^ array:1 [▼
  0 => array:3 [▼
    "query" => "select * from `users`"
    "bindings" => []
    "time" => 2.46
  ]
]

Example 3

Here we'll repeat the step2, rather we'll produce the nested array in flat array. Or in other words if we want to say, we'll flatten the array of step2 result. So let's see below code.

public function example3()
    {
        DB::enableQueryLog();

        $users = User::select("*")->get();
        $query = DB::getQueryLog();

        $query = end($query);

        dd($query);
    }

Here what we'll do is that, we'll only dd() the last array of getQueryLog() array. While we'll dd() the whole getQueryLog() array in step2. So, it'll produce the below output.

^ array:3 [▼
  "query" => "select * from `users`"
  "bindings" => []
  "time" => 2.36
]

That's it for today. I hope you'll enjoy this tutorial and it'll help you to debug the whole project and help to improve the performance. Thanks for reading. 🙂