You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

搜索参数为空时避免返回全部数据表记录的解决方法

解决搜索框为空时返回空结果的问题

你可以通过以下两种方式实现需求:

方式一:直接判断搜索值是否为空

先检查搜索内容是否为空(包含仅输入空格的情况),为空则直接返回空集合,否则执行模糊查询:

public function search(Request $request)
{
    $search = trim($request->input('search'));
    
    if (empty($search)) {
        // 搜索值为空,返回空集合
        $client = collect();
    } else {
        $client = ClientModel::where('name', 'LIKE', "%{$search}%")->get();
    }
    
    return view('search', compact('client'));
}

方式二:使用Laravel查询构造器的条件分支

通过when方法设置条件分支,当搜索值为空时,添加一个永远不成立的查询条件,确保返回空结果:

public function search(Request $request)
{
    $search = trim($request->input('search'));
    
    $client = ClientModel::when($search, 
        // 搜索值不为空时,执行模糊查询
        function ($query) use ($search) {
            $query->where('name', 'LIKE', "%{$search}%");
        },
        // 搜索值为空时,添加无效条件返回空集合
        function ($query) {
            $query->whereRaw('1 = 0');
        }
    )->get();
    
    return view('search', compact('client'));
}

内容的提问来源于stack exchange,提问作者Yagatekimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:20:38