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

Laravel搜索表单无结果问题:如何修复办公室检索功能?

修复Office搜索功能的分步方案

咱们先从明显的问题入手,再逐步调整逻辑,让搜索功能正常工作:

1. 先修复HTML语法错误

你在Building.blade.php的搜索按钮里多了一个未闭合的</i>标签,这会导致HTML结构无效,可能直接影响表单提交:

<!-- 错误代码 -->
<button type="submit" class="btn btn-info btn-md">Search</i>
<!-- 修正后 -->
<button type="submit" class="btn btn-info btn-md">Search</button>

2. 调整Building页面的搜索逻辑(让结果在当前页展示)

目前你的Building页面搜索表单提交到/offices路由,会跳转到独立的search视图,但你应该是想在当前建筑页面展示该建筑下的搜索结果对吧?那需要修改表单提交地址和对应控制器逻辑:

2.1 修改Building.blade.php的表单提交地址

把表单的提交目标改成当前建筑的路由,确保提交后停留在当前页面:

{!! Form::open(['method'=> 'GET','url'=>route('building', $building->id),'role'=>'search']) !!}

2.2 更新PageController@show方法,加入搜索处理

在PageController的show方法里,添加搜索逻辑,只筛选当前建筑下的办公室:

public function show($id) {
    $building = Building::findOrFail($id);
    $search = \Request::get('search');
    
    // 先关联当前建筑的办公室,再根据关键词过滤
    $officesQuery = $building->offices();
    if ($search) {
        $officesQuery = $officesQuery->where('name','like','%'.$search.'%');
    }
    $offices = $officesQuery->get();
    
    return view('building', compact('building', 'offices', 'search'));
}

3. 处理无搜索结果的页面状态

如果没有匹配的办公室,页面会因为空集合遍历而无内容,你可以加入空状态提示:

<tbody>
@if($offices->isEmpty())
    <tr>
        <td colspan="3" class="text-center">没有找到匹配的办公室</td>
    </tr>
@else
    @foreach($offices as $office)
    <tr>
        <td>{{optional($office)->name}}</td>
        <td>{{$office->floor}}</td>
        <td class="a">
            @if(!Auth::guest())
            <a href="{{route('editofficeform', ['id'=>$building->id, 'office_id'=>$office->id])}}" class="btn btn-success btn-sm">Edit</a>
            <a href="{{route('deleteoffice', $office->id)}}" class="btn btn-danger btn-sm">Delete</a>
            @endif
        </td>
    </tr>
    @endforeach
@endif
</tbody>

4. 优化独立搜索页面的逻辑(如果需要保留search.blade.php)

如果你还是需要独立的搜索页面,调整OfficeController@index确保空搜索时也能返回数据:

public function index() {
    $search = \Request::get('search');
    // 用when方法简化条件判断,空搜索时返回所有办公室
    $offices = Office::when($search, function($query) use ($search) {
        return $query->where('name','like','%'.$search.'%');
    })->get();
    
    return view('search',compact('offices','search'));
}

这样调整后,Building页面的搜索会在当前页展示该建筑下的匹配结果,不会跳转,也能正确处理无结果的情况;独立搜索页的逻辑也会更健壮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:01:07