81
use App\Order;
 
public function show(Order $order) {
    $data = $order->all();
    return dd($order->getQueryLog());

Is there any way to display the query built by Eloquent in Laravel?

I tried getQueryLog(); but its not working

julianstark999
  • 3,450
  • 1
  • 27
  • 41
Benjamin W
  • 2,658
  • 7
  • 26
  • 48
  • Possible duplicate of [How to get the query executed in Laravel 5 ? DB::getQueryLog returning empty array](http://stackoverflow.com/questions/27753868/how-to-get-the-query-executed-in-laravel-5-dbgetquerylog-returning-empty-arr) – Raunak Gupta Dec 14 '16 at 13:23

12 Answers12

176

First you have to enable query log it can be done using

DB::connection()->enableQueryLog();

then you can use below code to see the query log

$queries = DB::getQueryLog();

if you want to see the last executed query

$last_query = end($queries);

to know more about logging see this https://laravel.com/docs/5.0/database#query-logging

Example

public function show(Order $order){
    \DB::connection()->enableQueryLog();
    $data = $order->all();
    $queries = \DB::getQueryLog();

    dd($queries);
}
lewis4u
  • 14,256
  • 18
  • 107
  • 148
kapilpatwa93
  • 4,111
  • 2
  • 13
  • 22
77

To see the query logs in laravel.log file, update app/Providers/AppServiceProvider.php

namespace App\Providers;

use DB;
use Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function($query) {
            Log::info(
                $query->sql,
                [
                    'bindings' => $query->bindings,
                    'time' => $query->time
                ]
            );
        });
    }

    // ...
}
DivinesLight
  • 2,398
  • 2
  • 24
  • 30
Muhammad
  • 6,725
  • 5
  • 47
  • 54
31

To use getQueryLog() you need to enable it first:

DB::enableQueryLog();
DB::getQueryLog();

If you want to see real queries, you can use Laravel Debugbar, it will show all real queries Laravel created during current request.

Sometimes ->toSql() is also useful.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
7

Working on 5.6, something like this in AppServiceProvider::boot()

    // Log all DB SELECT statements
    // @codeCoverageIgnoreStart
    if (!app()->environment('testing') && config('app.log_sql')) {
        DB::listen(function ($query) {
            if (preg_match('/^select/', $query->sql)) {
                Log::info('sql: ' .  $query->sql);
                // Also available are $query->bindings and $query->time.
            }
        });
    }

Then in config/app.php, just so it's easy to enable/disable from amending the .env

    'log_sql' => env('LOG_SQL'),

All credit to: https://arjunphp.com/laravel-5-5-log-eloquent-queries/

And this can be parsed for unique queries with:

    grep ") sql:" laravel.log | sed -e "s#.*select\(.*\)\[\]#select\1#" | sort -u
markdwhite
  • 2,360
  • 19
  • 24
5

write this before the query DB::enableQueryLog();

DB::enableQueryLog();

$data = $order->all();

$query = DB::getQueryLog();

dd($query);
Code Lღver
  • 15,573
  • 16
  • 56
  • 75
Abid Shah
  • 325
  • 3
  • 5
4

I know it's an old question, but it might help others that had the same issue I had.

If you use other connection than the default one, you should specify it to get the query log properly.

\DB::connection('YourConnection')->enableQueryLog();
$test = MyModel::all();
$queries = \DB::connection('YourConnection')->getQueryLog();
dd($queries);
Juliano
  • 63
  • 9
3

You can use this package https://github.com/supliu/laravel-query-monitor

After installing, open the terminal and run the command:

php artisan laravel-query-monitor

All queries executed by Eloquent will be displayed in real time

Alex
  • 32,506
  • 16
  • 106
  • 171
3

Query Execution

\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {          
            $sql = $query->sql; 
            $time = $query->time;
            $connection = $query->connection->getName();
 
            Log::debug('query : '.$sql);
            Log::debug('time '.$time);
            Log::debug('connection '.$connection);
        });

Query

StaffRegister::all();

Output

[2021-03-14 08:00:57] local.DEBUG: query : select * from `staff_registers`  
[2021-03-14 08:00:57] local.DEBUG: time 0.93  
[2021-03-14 08:00:57] local.DEBUG: connection mysql  

complete structure

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use App\Models\StaffRegister;

class AuthController extends Controller
{
   public function index(){
   
       \Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
      
           $sql = $query->sql; 
           $time = $query->time;
           $connection = $query->connection->getName();

           Log::debug('query : '.$sql);
           Log::debug('time '.$time);
           Log::debug('connection '.$connection);
       });

       $obj = StaffRegister::all(); 
    
       return $obj;
   }
}

Accurate Method

Mohamed Raza
  • 818
  • 7
  • 24
2

You can use my Laravel package which is work perfectly in Larave 6 and 7. (Not sure about laravel 5 or less.)

For use Install the package via composer: by following command

composer require dipenparmar12/laravel-query-log

restart server. after this you will see

storage/logs/db-query.log file containing your query logs.

For more details visit Laravel-query-log

Thanks

dipenparmar12
  • 3,042
  • 1
  • 29
  • 39
1

You can use ::toSql() or ->toSql() as demonstrated below:

use App\Order;

public function show(Order $order){

    return $order::toSql();

Or

use App\Order;

public function show(Order $order){

    return $order::where("id", "<>", 0)->toSql();

You might have to enable query log:

DB::enableQueryLog();
Elisha Senoo
  • 3,489
  • 2
  • 22
  • 29
0

If you are using Laravel 6+ (i have not checked below 6), you can use

// show sql and bindings  +  stop execution
DB::table('your_table')->dd();   

// show sql and bindings
DB::table('your_table')->dump(); 

https://laravel.com/docs/7.x/queries#debugging

Bissel
  • 1
  • 1
0

An easy and quick way I use for check queries during development is to make a voluntary mistake in one of the name of the columns of group or order sentences and then the sql query will be shown on the upper left frame of the debugger window.

It is not perfect because the datetimes are not shown with the "'", but it is easy, fast and doesn't require to add or enable anything additional.

hanscker
  • 1
  • 1