How to Get Last Executed Query in Laravel?
Hi dev,
Let's look at a brief example using the Laravel 9 Eloquent Get Query Log. In this tutorial, we'll show you how to get a simple SQL query in Laravel . You'll find a straightforward example of the Laravel 9 print last SQL query in this post. You'll find a straightforward illustration of an elegant print last query in Laravel 9 in this post.
In Laravel 9, I'll use toSql(), DB::enableQueryLog(), and DB::getQueryLog to print the most recent SQL query. I'll also display the results of the print sql query.
So, let's see the examples below and use them as you want anyone.
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...
- 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