Laravel Eloquent display query log in php

In this article we will learn about log query in Laravel.  It helps us to view the query of laravel application. Sometime we want  to display last executed query in laravel application for debug.

While working with project then sometime we need to display some log query  so that we need to check the query is correct or not . it reduces our time while debugging the code.

Lets see the following example of eloquent query in laravel.

  1. toSql()
  2. DB::enableQueryLog()
  3. DB::getQueryLog()
  1. toSql() :

We will see the example of toSql() query . while we working with database query then we need to see the query that is correct or not that why we should use toSql().

Example 1 ( Controller Code )

$query = User::select("*")->toSql();                                                                                                                                                                                     dd($query);

Output

select * from `users`
  1. DB::enableQueryLog()

While working with DB query builder the we should use this db enable query. we have to use this package "use Illuminate\Support\Facades\DB"

Example 2. (controller Code)

use Illuminate\Support\Facades\DB;”  
...
...
public function show(){
      DB::enableQueryLog();
      $arr_user = DB::table('users')->select('name', 'email as user_email')->get();
     // same will work for Eloquent
     // $user = User::find(1);
       dd(DB::getQueryLog());
}

Output

array:1 [▼ // app/Http/Controllers/Api/ContactController.php:28
  0 => array:3 [▼
"query" => "select `name`, `email` as `user_email` from `users`"
    "bindings" => []
    "time" => 11.0
    ]
] 

Example 2 ( Controller code )

DB::enableQueryLog();
$users = User::select("*")->get();
$quries = DB::getQueryLog();
dd($quries);

Output

array:1 [▼
     0 => array:3 [▼
     "query" => "select * from `users`"
     "bindings" => []
     "time" => 4.25
    ]
]
  1. DB::getQueryLog()

This is the another example of query builder in laravel in which we can use “DB::getQueryLog()” to get query. It will execute in short time in compression toDB::enableQueryLog();

    DB::enableQueryLog();
        $users = User::select("*")->get();
        $query = DB::getQueryLog();
       $query =end($query);
       dd($query);

Output 

array:3 [▼
   "query" => "select * from `users`"
    "bindings" => []
    "time" => 2.07
   ] 

Thank you reading this article , Hope it will helpful to you ..!