How to Get Last Executed Query in Laravel 8?
This simple article demonstrates of get sql query in laravel 8. step by step explain laravel 8 print last sql query. I’m going to show you about laravel 8 eloquent print last query. let’s discuss about laravel 8 last executed query. let's see here laravel 8 get last executed query.
I will print last sql query in laravel 8 using toSql(), DB::enableQueryLog() and DB::getQueryLog(). i will also show you output of print sql query.
So, let's see examples bellow and use as you want any one.
Example 1:
Controller Code:
<?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:
select * from `users`
Example 2:
Controller Code:
<?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:
array:1 [â–¼
0 => array:3 [â–¼
"query" => "select * from `users`"
"bindings" => []
"time" => 4.25
]
]
Example 3:
Controller Code:
<?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:
array:3 [â–¼
"query" => "select * from `users`"
"bindings" => []
"time" => 2.07
]
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 8 Clear Cache of Route, View, Config Command Example
- Laravel 8 Import Export Excel and CSV File Tutorial
- Laravel 8 Pagination Example Tutorial
- Laravel 8 Livewire CRUD with Jetstream & Tailwind CSS
- Laravel 8 Authentication using Jetstream Example
- Laravel 8 Multiple Image Upload Tutorial
- Laravel 8 CRUD Application Tutorial for Beginners
- Delete All Records from Table in Laravel Eloquent
- Laravel Eloquent inRandomOrder() Method Example
- Laravel Eloquent whereNull() Query Example
- Laravel One to Many Eloquent Relationship Tutorial
- Laravel Many to Many Eloquent Relationship Tutorial