laravel 5.8 不搜索任何东西就回显

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


<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 . '%');

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


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



}


慕田峪9158850
浏览 71回答 1
1回答

繁花如伊

解决方案很简单,只是不要将 $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 辅助函数返回给定值是否不是“空白”链接
打开App,查看更多内容
随时随地看视频慕课网APP