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

Laravel搜索无结果时显示提示消息的实现方案

没问题,这个需求实现起来超简单,分两步就能搞定——先在控制器里处理搜索结果的状态判断,再在视图里根据状态渲染对应的内容就行:

1. 先处理OfficeController.php里的逻辑

假设你现在的控制器代码是通过搜索关键词查询建筑数据,咱们只需要新增一个判断结果是否为空的变量,再把它传给视图:

public function search(Request $request)
{
    $query = $request->input('search');
    // 执行搜索查询
    $buildings = Building::where('name', 'like', "%{$query}%")->get();
    
    // 新增:判断搜索结果是否为空
    $hasResults = !$buildings->isEmpty();
    
    // 将结果和状态变量一起传给视图
    return view('buildings', compact('buildings', 'hasResults'));
}

核心就是用isEmpty()方法判断查询返回的集合是否为空,把这个状态标记$hasResults传递给视图层。如果你的搜索逻辑是写在index方法里而非单独的search方法,逻辑也是完全一致的。

2. 接着修改buildings.blade.php的视图逻辑

在视图里用Laravel的Blade指令做条件分支:有结果就渲染表格,没结果就展示提示文字:

<!-- 你的搜索表单保持不变 -->
<form action="{{ route('buildings.search') }}" method="get">
    <input type="text" name="search" placeholder="搜索建筑...">
    <button type="submit">搜索</button>
</form>

<!-- 结果展示区域 -->
@if($hasResults)
    <table>
        <thead>
            <tr>
                <th>建筑名称</th>
                <th>地址</th>
                <!-- 其他你需要的表头字段 -->
            </tr>
        </thead>
        <tbody>
            @foreach($buildings as $building)
                <tr>
                    <td>{{ $building->name }}</td>
                    <td>{{ $building->address }}</td>
                    <!-- 其他你需要的表格内容 -->
                </tr>
            @endforeach
        </tbody>
    </table>
@else
    <!-- 无搜索结果时的提示 -->
    <div style="padding: 20px; text-align: center; color: #666;">
        *Not found* - 没有找到匹配的建筑,请尝试其他搜索关键词
    </div>
@endif

这样用户搜索不到内容时,就会看到清晰的提示,而不是空表格了。你还可以给提示区域加个CSS类,自定义样式让它更显眼。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:27:31