如果无法找到任何一个,如何在搜索中显示消息,Laravel

时间:2018-02-10 12:16:57

标签: php laravel

所以我有这个搜索表单,我想显示一条消息,如果用户输入数据库中不存在的内容,如“找不到”这样的消息会导致我现在所拥有的只显示空表如果它没有找不到任何东西。我该怎么做?这是我的搜索表单的代码

buildings.blade.php

{!! Form::open(['method'=> 'GET','url'=>'offices','role'=>'search']) !!}
    <div class="input-group col-xs-4 col-md-6" >
        <input type="text" name="search" class="form-control" placeholder="Search..." required>
        <span class="input-group-btn">
            <button type="submit" class="btn btn-info btn-md">
                <span class="glyphicon glyphicon-search"></span> Search
            </button>
        </span>
    </div>
{!! Form::close()!!}

OfficeController.php

public function index(Request $request) {
    $search = \Request::get('search');
    $offices = Office::where('name', 'LIKE', '%' . $search . '%')->get(); 
    return view('search', compact('offices', 'search')); 
}

2 个答案:

答案 0 :(得分:2)

在视图中执行此操作:

@if ($offices->isEmpty())
    Not Found
@elseif
    {{-- Show offices --}}
@endif

您还可以使用以下方法之一进行检查:

@if (count($offices) === 0)
@if ($offices->count() === 0)
@if (empty($offices))

答案 1 :(得分:0)

您可以在会话中闪烁消息并在视图中有条件地显示:

public function index(Request $request)
{
    $search = \Request::get('search');
    $offices = Office::where('name','LIKE','%'.$search.'%')->get();
    if (!$offices || !$offices->count()) {
        Session::flash('no-results', 'Your search produced no results');
    }
    return view('search',compact('offices','search')); 
}

然后在您的视图文件中:

@if(Session::has('no-results'))
    <span>{{ Session::get('no-results') }}</span>
@else
    // put the table in here. 
@endif