如何进行 Laravel 5 数据库搜索,但如果页面在没有搜索的情况下加载,则返回所有


How to do a Laravel 5 database search but return all if the page has loaded without a search

>我希望创建一个带有搜索栏的客户页面。如果未进行搜索,则将返回所有内容。下面的代码显示了我的控制器中的内容。

public function index(Request $request)
     {
          if(($term = $request->get('term'))){
              $customers = customers::where('name', 'like', '%' .$term.'%'); 
          }
            else{
              $customers = customers::all();  
            }     
         return view ("customers.index")->with('customers',$customers);
}

加载时返回所有内容,但在搜索时,视图中的表中不显示任何内容。没有错误,表单正在传递数据,只是搜索后不会在视图中加载数据。

下面是视图的代码。

<tbody>
                @foreach ($customers as $customer)
                    <tr>
                        <th>{{$customer->id}}</th>
                        <td>{{$customer->business}}</td>
                        <td>{{$customer->name}}</td>
                        <td><a href="{{ route ('customers.show', $customer->id)}}" class="btn btn-default">View</a></td>
                    </tr>
                @endforeach
            </tbody>    

谢谢。

搜索结束时缺少get()方法。它应该是:

$customers = customers::where('name', 'like', '%' .$term.'%')->get();

这将根据结果返回collection

相关文章: