To get the query from an Eloquent call without actually running it, you can use the toSql()
method. This is useful when you only need to see the query and don't want to modify data. However, keep in mind that for complex queries or sub-queries, the toSql()
method may not display the entire query.
$users = User::query()
->where('is_active', 1)
->with(‘profile’)
->latest()
->limit(5)
->toSql();
select * from `users` where `is_active` = ? and `users`.`deleted_at` is null order by `created_at` desc limit 5
The second method in Laravel is the query log, which gathers all queries made during a request. To use it, enable the log, execute your query, and check the output.
use Illuminate\Support\Facades\DB;
DB::enableQueryLog();
$user = User::query()
->where('is_active', 1)
->with('profile')
->latest()
->limit(5)
->get();
dd(DB::getQueryLog());
Output:
array:2 [ // app/Models/User
0 => array:3 [
"query" => "select * from `users` where `is_active` = ? and `users`.`deleted_at` is null order by `created_at` desc limit 5"
"bindings" => array:1 [
0 => 1
]
"time" => 5.6
]
1 => array:3 [
"query" => "select * from `profiles` where `profiles`.`membership_type` = ? and `profiles`.`user_id` = ? and `profiles`.`deleted_at` is null"
"bindings" => array:1 [
0 => 0,
1 => 1
]
"time" => 1.38
]
]
This provides detailed info about the executed query and its execution time. If the query has data bindings, the log displays them, making it convenient to verify your data.
Use dd
and dump
methods when building a query to see current query bindings and SQL. dd
stops the request and displays debug info, while dump
shows debug info but allows the request to continue.
// using dd()
$user = User::query()
->where('is_active', 1)
->with('profile')
->latest()
->limit(5)
->dd();
// using dump()
$user = User::query()
->where('is_active', 1)
->with('profile')
->latest()
->limit(5)
->dump();
Output:
select * from `users` where `is_active` = ? and `users`.`deleted_at` is null order by `created_at` desc limit 5
array:1 [
0 => 1
]