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.
- toSql()
- DB::enableQueryLog()
- DB::getQueryLog()
-
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`
-
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
]
]
-
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 ..!
Latest Post
Upload Image in MySQL database using Node js and React js
How to add new column to existing table without losing data in Laravel
Laravel Eloquent display query log in php
What is traits in PHP with example
How to disable click outside modal to close modal in bootstrap
Auto refresh code in HTML using meta tags
How to Optimize the Speed & Performance of a Laravel Website