In this tutorial you will learn about the How to Get Last Executed Query in Laravel 8 and its application with practical example.
In this How to Get Last Executed Query in Laravel 8 tutorial I will show you how to get or print last executed query in laravel application. In this tutorial you will learn to display or print last executed query in your laravel 8 application. In this article I will share various example to display or print last executed sql query in laravel. In this examples we will be using toSql(), DB::enableQueryLog() and DB::getQueryLog() to output of print sql query. These examples we will help us to debug last executed sql query in laravel.
How to Get Last Executed Query in Laravel 8
In this step by step tutorial I will demonstrate you with example to print or output last executed query in laravel application. We will use sql query in laravel 8 using toSql(), DB::enableQueryLog() and DB::getQueryLog(). Please follow the instruction given below:
Example 1:-
Please put the following code in your controller code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php namespace App\Http\Controllers; use App\Models\User; class UserController extends Controller { /** * Create a new controller instance. * * @return void */ public function redirectToGoogle() { $query = User::select("*")->toSql(); dd($query); } } |
Output:-
1 |
select * from `users` |
Example 2:-
Please put the following code in your controller code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace App\Http\Controllers; use App\Models\User; use DB; class UserController extends Controller { /** * Create a new controller instance. * * @return void */ public function redirectToGoogle() { DB::enableQueryLog(); $users = User::select("*")->get(); $quries = DB::getQueryLog(); dd($quries); } } |
Output:-
1 2 3 4 5 6 7 |
array:1 [▼ 0 => array:3 [▼ "query" => "select * from `users`" "bindings" => [] "time" => 4.25 ] ] |
Example 3:-
Please put the following code in your controller code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace App\Http\Controllers; use App\Models\User; use DB; class UserController extends Controller { /** * Create a new controller instance. * * @return void */ public function redirectToGoogle() { DB::enableQueryLog(); $users = User::select("*")->get(); $query = DB::getQueryLog(); $query = end($query); dd($query); } } |
Output:-
1 2 3 4 5 |
array:3 [▼ "query" => "select * from `users`" "bindings" => [] "time" => 2.07 ] |