In this post, I will show you how to get the last executed SQL query in a Laravel 12 application.
We will print the last SQL query in Laravel 12 using `ddRawSql()`, `toSql()`, `DB::enableQueryLog()`, and `DB::getQueryLog()`. We can use those functions in the controller to print the last executed SQL query.
How to Get Last Executed Query in Laravel 12
Example 1:
We can use the `ddRawSql()` Eloquent function to get the last executed query. `ddRawSql()` 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("*")->ddRawSql();
dd($query);
}
}
Output:
select * from `users`
Example 2:
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 3:
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 4:
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:
Read Also How to Upload Multiple Images in Laravel 12 Example
array:3 [
"query" => "select * from `users`"
"bindings" => []
"time" => 2.07
]
I hope it can help you…