Laravel 5.3 中的搜索栏过滤表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41014940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search bar in Laravel 5.3 to filter the table
提问by leo0019
1) I added the search bar to the view :
1)我在视图中添加了搜索栏:
{!! Form::open(['method'=>'GET','url'=>'home','class'=>'navbar-form navbar-left','role'=>'search']) !!}
<div class="input-group custom-search-form">
<input type="text" class="form-control" name="search" placeholder="Search...">
<span class="input-group-btn">
<button class="btn btn-default-sm" type="submit">
<i class="fa fa-search">i
</button>
</span>
2) In my controller I'm displaying all my users in a table and the search bar is on top of it
2)在我的控制器中,我将所有用户显示在一个表格中,搜索栏位于它的顶部
public function index()
{
$user = User::all();
$search = \Request::get('search'); the param of URI
$users = User::where('name','=','%'.$search.'%')
->orderBy('name')
->paginate(20);
return view('home',compact('users'))->withuser($user);
}
Here is what the table looks like
这是桌子的样子
@foreach($user as $users)
<th scope="row">1</th>
<td><a href="{{ url('/user').'/'.$users->id }}">show</a></td>
<td>{{$users->name}}</td>
<td>{{$users->city}}</td>
<td>{{$users->phone}}</td>
<td>{{$users->street}}</td>
<td>{{$users->national_id}}</td>
<td>{{$users->name}}</td>
</tr>
@endforeach
What I'm trying to get is when I search in the bar I want to do a loop like this @foreach($users as $user) {{ $user->name }} @endforeach and replace the view to the searched names only. and here is the route for the index
我想要得到的是,当我在栏中搜索时,我想做一个这样的循环 @foreach($users as $user) {{ $user->name }} @endforeach 并将视图替换为搜索的名称只要。这是索引的路线
Route::get('/home', 'HomeController@index');
how can I achive that ? sorry for the long question in advance.
我怎样才能做到这一点?很抱歉提前提出了很长的问题。
回答by Alexey Mezenin
You need to use like
instead of =
:
您需要使用like
代替=
:
$users = User::where('name', 'like', '%'.$search.'%')
->orderBy('name')
->paginate(20);
Also, you're trying to create two queries. Much better way is to create local scope:
此外,您正在尝试创建两个查询。更好的方法是创建本地范围:
public function scopeSearch($q)
{
return empty(request()->search) ? $q : $q->where('name', 'like', '%'.request()->search.'%');
}
And then use it in controller:
然后在控制器中使用它:
public function index()
{
$users = User::search()->orderBy('name')->paginate(20);
return view('home', compact('users'));
}
This code will paginate all users if there is no search parameter or it will filter users and paginate them.
如果没有搜索参数,此代码将对所有用户进行分页,否则将过滤用户并对其进行分页。