Laravel How to Get Last Executed Query
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. 🙂
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)