How to Have Laravel Eloquent or Query Builder Output Raw SQL


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?


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

I believe the most recent queries will be at the bottom of the array.

You will have something like that:

array(1) {
  array(3) {
    string(21) "select * from "users""
    array(0) {
    string(4) "0.92"

About the author