DEV Community

TRUNG VU
TRUNG VU

Posted on

How to get raw sql that is being executed with binded data

Sometime we need to print executed queries in Laravel application for debug, I will give methods of how to show it.

Method 1

In controller:

$posts = Post::whereActive(1);
dd($posts->toSql(), $posts->getBindings());
Enter fullscreen mode Exit fullscreen mode

Output:

"select * from `posts` where `status` = ?"

array:1 [▼
  0 => 1
]
Enter fullscreen mode Exit fullscreen mode

Method 2

In controller:

DB::enableQueryLog();
$posts = Post::active()->paginate(5);
$query = DB::getQueryLog();
dd($query);
Enter fullscreen mode Exit fullscreen mode

Output:

array:2 [▼
  0 => array:3 [▼
    "query" => "select count(*) as aggregate from `posts` where `status` = ?"
    "bindings" => array:1 [▼
      0 => 1
    ]
    "time" => 0.3
  ]
  1 => array:3 [▼
    "query" => "select * from `posts` where `status` = ? limit 5 offset 0"
    "bindings" => array:1 [▼
      0 => 1
    ]
    "time" => 0.3
  ]
]
Enter fullscreen mode Exit fullscreen mode

Method 3

In controller:

use Illuminate\Support\Facades\DB;

DB::listen(function ($query) {
    dump($query->sql,$query->bindings);
});
$post = Post::ofSlug($slug)->active()->firstOrFail();
Enter fullscreen mode Exit fullscreen mode

Output:

"select * from `posts` where `slug` = ? and `status` = ? limit 1"

array:2 [▼
  0 => "create-custom-helper-class-in-laravel-7"
  1 => 1
]
Enter fullscreen mode Exit fullscreen mode

Happy Coding :)

Top comments (0)