How to view raw SQL of Laravel query?

There are a number of ways to view the raw SQL statement of your Larael query builder

->dd()

A simple way to show you the SQL statement along with its binding is replacing ->get(), first(), .. with ->dd(), here is an example:

$users = User::select('name')
                  ->where('id', '<', 20)
                  ->where('is_active', 1)
                  ->dd();

and the output will be like this:

"select `name` from `users` where `id` < ? and `is_active` = ?"
array:2 [▼
  0 => 20
  1 => 1
]

->toSql() , getBindings()

instead of ->get() you add ->toSql to get the query and getBindings() to get the SQL bindings, here is an example:

$query = User::select('name')
                  ->where('id', '<', 20)
                  ->where('is_active', 1);

dd($query->toSql(), $query->getBindings());

DebugBar

DebugBar A very useful tool that shows all queries, including binding + timing for all queries on the page

DB::enableQueryLog();

Another method to show raw SQL in Laravel is to use DB::enableQueryLog();. You need to enable it before the query

DB::enableQueryLog();
$users = User::select('name')
                  ->where('id', '<', 20)
                  ->where('is_active', 1)
                  ->get();
$query = DB::getQueryLog();
dd($query);

ad the result would be:

array:1 [▼
  0 => array:3 [▼
    "query" => "select `name` from `users` where `id` < ? and `is_active` = ?"
    "bindings" => array:2 [▼
      0 => 20
      1 => 1
    ]
    "time" => 0.47
  ]
]

Leave a Reply

Your email address will not be published.