How to Get Last Executed Query in Laravel 8?

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

This simple article demonstrates of get sql query in laravel 8. step by step explain laravel 8 print last sql query. I’m going to show you about laravel 8 eloquent print last query. let’s discuss about laravel 8 last executed query. let's see here laravel 8 get last executed query.

I will print last sql query in laravel 8 using toSql(), DB::enableQueryLog() and DB::getQueryLog(). i will also show you output of print sql query.

So, let's see lessons bellow and use as you want any one.

Lesson 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);

}

}

Result:-

select * from `users`

Lesson 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);

}

}

Result:-

array:1 [▼

0 => array:3 [▼

"query" => "select * from `users`"

"bindings" => []

"time" => 4.25

]

]

Lesson 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);

}

}

Result:-

array:3 [▼

"query" => "select * from `users`"

"bindings" => []

"time" => 2.07

]

thank you very much for following up with me.

Recent Posts

Related Posts