Когда-нибудь нам понадобится распечатать выполненные запросы в приложении Laravel для отладки, я приведу методы, как это показать.
Способ 1
В контроллере:
$posts = Post::whereActive(1); dd($posts->toSql(), $posts->getBindings());
Выход:
"select * from `posts` where `status` = ?" array:1 [▼ 0 => 1 ]
Способ 2
В контроллере:
DB::enableQueryLog(); $posts = Post::active()->paginate(5); $query = DB::getQueryLog(); dd($query);
Выход:
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
]
]
Способ 3
В контроллере:
use Illuminate\Support\Facades\DB;
DB::listen(function ($query) {
dump($query->sql,$query->bindings);
});
$post = Post::ofSlug($slug)->active()->firstOrFail();
Выход:
"select * from `posts` where `slug` = ? and `status` = ? limit 1" array:2 [▼ 0 => "create-custom-helper-class-in-laravel-7" 1 => 1 ]
Счастливого кодирования:)
Оригинал: “https://dev.to/vumanhtrung/how-to-get-raw-sql-that-is-being-executed-with-binded-data-2i9n”