Using Multiple where Clauses in Laravel for Multi-Field Search
This article demonstrates how to perform multi‑field searches in Laravel by chaining multiple where clauses with closure callbacks, showing example code that conditionally filters by username and hospital ID based on request parameters.
Sometimes a project needs to search across several fields; Laravel provides a straightforward way to achieve this by using multiple where clauses.
In Laravel you can call where() repeatedly, assigning a separate clause to each field, and inside each where you can place a closure that checks whether the corresponding request parameter is present.
The following example shows how to build a query that optionally filters by a username and a hospital ID, only adding the conditions when the request values are not empty.
$username = '';
// 收货人姓名
$hospital_id = '';
// 医院id
# 判断是否有姓名搜索
if (!empty($request->username)) {
$username = $request->username;
}
# 判断是否有医院搜索
if (!empty($request->hospital_id)) {
$hospital_id = $request->hospital_id;
}
# 执行
$data = DB::table('test')
->where(function($query) use ($username){
# 进行判断
if (!empty($username)) {
$query->where('username','Like',"%$username%");
}
})
->where(function($query) use ($hospital_id){
# 进行判断
if (!empty($hospital_id)) {
$query->where('hospital_id','=', $hospital_id);
}
})
->get()
->toArray();
dd($data);The query returns the matching rows as an array, and the dd() function is used to dump the result for debugging.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
