为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕田峪9158850 2023-06-18 16:06:18
我有一个小问题,即使没有搜索键也会显示搜索结果。这是片段。这是观点:<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'));}
查看完整描述

1 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

解决方案很简单,只是不要将 $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 辅助函数返回给定值是否不是“空白”链接


查看完整回答
反对 回复 2023-06-18
  • 1 回答
  • 0 关注
  • 67 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信