How to get raw SQL query in Laravel


Using eloquent in laravel is very convenient, but sometimes you want to know the raw SQL query that's executed behind the scene, so how to get raw SQL query from laravel eloquent?

Luckily, laravel provide a way to get the SQL query from a running eloquent query, there is method called getQueryLog(), we can use this to get the SQL query in laravel.

What you need to do is run the DB::getQueryLog() after executing eloquent query, here's an example:
$users = User::get();
print_r(DB::getQueryLog());
Output of the code above, is something like this:
Array ( [0] => Array ( [query] => select * from `users` [bindings] => Array ( ) [time] => 0.76 ) )

Another example:
$users = User::where('id', '<=', 10)
   ->take(2)->skip(2)->get();
print_r(DB::getQueryLog());

The output:
Array ( [0] => Array ( [query] => select * from `users` where `id` <= ? limit 2 offset 2 [bindings] => Array ( [0] => 10 ) [time] => 0.84 ) )

The laravel getQueryLog method not only shows the raw SQL query but also the data bindings and the execution time of the query itself.


EmoticonEmoticon