laravel 5.8 不搜索任何内容就回显

laravel 5.8 echoing out without searching anything

我有一个小问题,即使没有搜索键也会显示搜索结果。这是片段。 这是观点:

<form action="/search" method="GET">
<div class="form-group search-location">
    <input type="text" name="cityKey" id="cityKey" value="{{ request()->input('cityKey') }}"
           class="form-control" >

</div>
<div class="form-group search-info">

    <input type="text" name="key" id="key" value="{{ request()->input('key') }}"
           class="form-control" >

</div>
<button type="submit" class="btn btn-primary search-btn"><i class="fas fa-search"></i>
    <span>search</span></button>

这是控制器:

public function search(Request $request){
    $cityKey = $request->cityKey;
    $key = $request->key;


    $doctors = Doctor_list::where('speciality_title', 'LIKE', '%' . $key . '%')->
    where('location', 'LIKE', '%' . $cityKey . '%')->
    orWhere('doctors_name', 'LIKE', '%' . $key . '%')->
    where('location', 'LIKE', '%' . $cityKey . '%')->
    orWhere('speciality_type', 'LIKE', '%' . $key . '%')->
    where('location', 'LIKE', '%' . $cityKey . '%');

//完成查询并使用 paginate 或 ->get() 终止查询 $doctors = $doctors->get();

    return view('search', compact('doctors'));


}

解决方案很简单,只是不要将 $doctors 变量传递给 view(或者更好的说法是传递并清空 var)并在 view 中检测到它为空并说没有搜索结果。这是代码:

public function search(Request $request){
    $cityKey = $request->cityKey;
    $key = $request->key;

    if (filled($cityKey) && filled($key)) {
        $doctors = Doctor_list::where('speciality_title', 'LIKE', '%' . $key . '%')->
        where('location', 'LIKE', '%' . $cityKey . '%')->
        orWhere('doctors_name', 'LIKE', '%' . $key . '%')->
        where('location', 'LIKE', '%' . $cityKey . '%')->
        orWhere('speciality_type', 'LIKE', '%' . $key . '%')->
        where('location', 'LIKE', '%' . $cityKey . '%')->
        get();
    }
    return view('search', [
        'doctors' => $doctors ?? []
    ]);
}

有了这个你甚至不用查询数据库。 filled 是一个 laravel 辅助函数 returns 是否给定值不是 "blank" 这里 link: https://laravel.com/docs/helpers#method-filled