Sometimes we need to view the the queries generated by
eloquent either for debugging purpose or to be sure that query generated is correct. To view queries in laravel 5, we have multiple ways.
First enable the query log as it is disabled by default.
DB::enableQueryLog();
Than at the end of your controller action method, you can use
use Illuminate\Support\Facades\DB; //Reference
//
//Execute queries.
//
print_r(DB::getQueryLog());
and the follow up code.
DB::enableQueryLog();
$users = DB::table('users')->get();
$query = DB::getQueryLog();
print_r($query);
Beside this, we can use toSql method and also use listen method. If you want to view all queries in a request, than use a listen method. Add following code in service provider boot method.
DB::listen(function($query) {
// $query->sql
// $query->bindings
// $query->time
//
echo ($query->sql);
});