【问题标题】:How to show message in search if cant find any, Laravel如果找不到任何消息,如何在搜索中显示消息,Laravel
【发布时间】:2018-02-10 12:16:57
【问题描述】:

所以我有这个搜索表单,如果用户输入数据库中不存在的内容,我想显示一条消息,例如“未找到”这样的消息,因为我现在拥有的只是显示一个空表,如果它没有什么都找不到。我怎么做这个?这是我的搜索表单的代码

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')); 
}

【问题讨论】:

  • 你运行的是什么版本的php?
  • 我的是 php 7.2.1 @btl

标签: php laravel


【解决方案1】:

在视图中执行此操作:

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

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

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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

    • 它说方法空不存在@btl
    • {!! Form::open(['method'=&gt; 'GET','url'=&gt;'offices','role'=&gt;'search']) !!} 我尝试将第二个放在此表单上方,但搜索表单未显示@btl
    • 当我尝试将其放入表单时,它什么也没有显示没有消息@btl
    • 它没有显示任何我应该将这个@if(Session::has('no-results')) &lt;span&gt;{{ Session::get('no-results') }}&lt;/span&gt; @endif 放在表单之前还是之后的位置? @btl
    • 我的意思是它没有显示任何消息只是一个空表@btl
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 2013-12-25
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多