Monday, January 18, 2016

How to view executed queries in laravel 5

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.


Than at the end of your controller action method, you can use

use Illuminate\Support\Facades\DB; //Reference
//Execute queries.

and the follow up code.

$users = DB::table('users')->get();
$query = DB::getQueryLog();

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);

No comments: