Laravel 9 - How to Get Last Executed Query

Laravel 9 - How to Get Last Executed Query

 Laravel 9 - How to Get Last Executed Query

Hello Artisans, today I'll talk about how to get the last executed query log. Which will also help us to see which raw SQL query is being executed. We'll also print the executed query through our Eloquent or any type of query which is 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 a flat array. Or in other words, if we want to say, we'll flatten the array of step2 results. So let's see the 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. 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 :)

StarCode Kh

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

Previous Post Next Post
close