Laravel 11 Get Last Executed Query Example
Teams applying “Laravel 11 Get Last Executed Query Example” in a production project can use employee incentives to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.
Before copying the example into a live application, confirm version-specific behaviour with the official Laravel website and test it against the project’s actual database and runtime.
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
]
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial