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

Laravel提交空搜索框不展示全部文章的问题如何解决?

问题根因

你当前使用的$request->has('s')判断逻辑存在问题:该方法仅判断请求中是否存在s参数,只要参数存在(哪怕值为空字符串、null)都会返回true。当你清空搜索框提交时,GET请求会携带s=的空参数,依然会进入搜索过滤逻辑,最终导致文章列表为空。

修复方案

将判断条件替换为$request->filled('s')即可,该方法会同时校验参数存在且不为空:

public function index(Request $request) {
    $posts = Post::get();
    if($request->filled('s')) {
        $query = strtolower($request->get('s'));
        $posts = $posts->filter(function ($post) use ($query) {
            return Str::contains(strtolower($post->Titel), $query);
        });
    }
    return view('posts.overview', ['posts' => $posts]);
}

优化建议(可选)

你当前的实现是先查询全量文章再通过集合过滤,数据量较大时性能开销很高。可以调整为在SQL查询阶段完成搜索筛选:

public function index(Request $request) {
    $posts = Post::when($request->filled('s'), function ($query) use ($request) {
        $searchKey = strtolower($request->get('s'));
        return $query->whereRaw('LOWER(Titel) LIKE ?', ["%{$searchKey}%"]);
    })->get();
    return view('posts.overview', ['posts' => $posts]);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:15:06