How to Get Query Log in Laravel Eloquent?

By Hardik Savani April 16, 2024 Category : Laravel MySql

Hi Developer,

This tutorial shows you how to get query log in laravel. you will learn how to log query in laravel. we will help you to give an example of how to check query in laravel. you can understand a concept of laravel get query log example.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

We have been many time need to get executed query log or you want to get last executed query or maybe if you want to diaplsy sql query from laravel query builder then you can do it that. so i have three example for display executed query in Laravel 5. when you are working on laravel application at that times , i think you need many time to print last run query or if you want to check direct from phpmyadmin sql box, so at that time you have to follow this three example. so, let's see three example of getting sql query from Laravel Query Builder.

Example 1:

In this example we can get directly get current sql query using toSql() of laravel query builder. In this example you don't need to enable query log or something you can directly query like bellow example:

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$user = User::where('id',1)->toSql();

dd($user);

}

}

Output:

select * from `users` where `id` = ?

Example 2:

Ok, In this example we must need to enable query log using DB::enableQueryLog() of Laravel Query builder. enableQueryLog() will give access to store all execute query in cache and we can get that query using DB::getQueryLog(). In this example you will get all query log not last only. bellow example how to use it together.

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use DB;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

DB::enableQueryLog();

$user = User::where('id',1)->get();

$query = DB::getQueryLog();

dd($query);

}

}

Output:

select * from `users` where `id` = ?

Example 3:

In this example i make the same as example 2, but you can get exactly last query using end(). so let's see how to use.

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use DB;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

DB::enableQueryLog();

$user = User::where('id',1)->get();

$query = end($query);

dd($query);

}

}

Output:

select * from `users` where `id` = ?

You can try any one....

Tags :
Shares