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 :)
Top comments (0)