Problem
How can I get an SQL query from my Laravel Eloquent or DB Query builder to find out what exactly my code is asking the database to show?
Solution
Yes. Whether you are a beginner and want to learn how Laravel Eloquent or Query Builder work under the hood or you simply need to generate an SQL for some other purpose, you can definitely go and extract that SQL query.
The way to do that is quick and easy:
To output to the screen the last queries ran you can use this:
DB::enableQueryLog(); // Enable query log
// Your Eloquent query executed by using get()
dd(DB::getQueryLog()); // Show results of log
// Your Eloquent query executed by using get()
dd(DB::getQueryLog()); // Show results of log
I believe the most recent queries will be at the bottom of the array.
You will have something like that:
array(1) {
[0]=>
array(3) {
["query"]=>
string(21) "select * from "users""
["bindings"]=>
array(0) {
}
["time"]=>
string(4) "0.92"
}
}
[0]=>
array(3) {
["query"]=>
string(21) "select * from "users""
["bindings"]=>
array(0) {
}
["time"]=>
string(4) "0.92"
}
}