03-Apr-2024
.
Admin
Hi, Dev
In this tutorial, I'll demonstrate the method to retrieve the last executed SQL query within a Laravel 11 application.
We'll demonstrate how to print the last SQL query in Laravel 11 using toSql(), DB::enableQueryLog(), and DB::getQueryLog(). These functions can be utilized within the controller to display the last executed SQL query. Let's examine each step with an example:
Example 1:
We can use the `toSql()` Eloquent function to get the last executed query. `toSql()` will return the SQL query, and you can print it.
<?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:
We can use `DB::enableQueryLog()` and `DB::getQueryLog()` functions to get the last executed SQL query. `DB::enableQueryLog()` function will enable the query log, and `DB::getQueryLog()` function will return query logs.
<?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:
We can use `DB::enableQueryLog()`, `DB::getQueryLog()`, and `end()` functions to get the last executed SQL query.
<?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...
#Laravel 11