In this article, We will know you how to get and print last query in laravel eloquent.
manytimes while working with laravel any project php framework you required to print last executed query for source code tetsing with debugging .
print last query in laravel
You can use laravel DB::getQueryLog() method to get all an executed sql queries if you want to get last executed then use end() method.
Before printing sql query log you required to first of all the enable it by using simple DB::enableQueryLog() method as well as then you can get all executed sql queries using Last Query In Laravel.
dd last query laravel
public function querylog() { \DB::enableQueryLog(); $list = \DB::table("products")->get(); $query = \DB::getQueryLog(); dd(end($query)); }
Results
Array ( [query] => select * from `products` [bindings] => Array ( ) [time] => 8.09 )
Example 1: laravel 5.6 get last query
In this laravel script we can get directly get current sql query using toSql() of laravel query builder. In this laravel script you don’t need to enable query log or something you can directly query like bellow laravel script:
$product = Product::where('is_active',1)->toSql(); print_r($product);
Example 2: laravel 5 eloquent print query
Ok, In this laravel script we must need to enable query log using DB::enableQueryLog() of Laravel Query builder. enableQueryLog() will give access to store all execute query in cache and we can get that query using DB::getQueryLog(). In this laravel script you will get all query log not last only. bellow laravel script how to use it together.
DB::enableQueryLog(); $product = Product::get(); $sqlQQ = DB::getQueryLog(); print_r($sqlQQ);
Example 3: laravel db query
In this laravel script We create the same as source code 2, but you can get exactly last query using end(). therefor let’s display how to use.
DB::enableQueryLog(); $product = Product::get(); $sqlQQ = DB::getQueryLog(); $sqlQQ = end($sqlQQ); print_r($sqlQQ);
I hope you get an idea about print last query in laravel.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.