How to Get Last Executed Query in Laravel 9?

By Hardik Savani November 5, 2023 Category : Laravel

In this quick example, let's see Laravel 9 Eloquent Get Query Log Example. This tutorial will give you a simple example of getting sql query in laravel 9. This post will give you a simple example of laravel 9 print last sql query. This article will give you a simple example of laravel 9 eloquent print last query.

I will print last sql query in laravel 9 using toSql(), DB::enableQueryLog() and DB::getQueryLog(). i will also show you output of 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...

Shares