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

Output:

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

array:1 [▼
0 => 1
]

Method 2

In controller:

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

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
]
]

Method 3

In controller:

use Illuminate\Support\Facades\DB;DB::listen(function ($query) {
dump($query->sql,$query->bindings);
});
$post = Post::ofSlug($slug)->active()->firstOrFail();

Output:

"select * from `posts` where `slug` = ? and `status` = ? limit 1"array:2 [▼
0 => "create-custom-helper-class-in-laravel-7"
1 => 1
]

Happy Coding :)

Full-Stack web developer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store