【问题标题】:Search bar in Laravel 5.3 to filter the tableLaravel 5.3 中的搜索栏来过滤表格
【发布时间】:2017-04-22 05:56:42
【问题描述】:

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) 在我的控制器中,我将所有用户显示在一个表格中,并且搜索栏位于其顶部

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

}

这是桌子的样子

 @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

我想要得到的是当我在栏中搜索时我想做这样的循环 @foreach($users 作为 $user) {{ $user->name }} @endforeach 并将视图替换为仅搜索到的名称。 这是索引的路线

    Route::get('/home', 'HomeController@index');

我怎样才能做到这一点?很抱歉提前问了这么长的问题。

【问题讨论】:

    标签: php html laravel search laravel-blade


    【解决方案1】:

    您需要使用like 而不是=

    $users = User::where('name', 'like', '%'.$search.'%')
        ->orderBy('name')
        ->paginate(20);
    

    另外,您正在尝试创建两个查询。更好的方法是创建local scope:

    public function scopeSearch($q)
    {
        return empty(request()->search) ? $q : $q->where('name', 'like', '%'.request()->search.'%');
    }
    

    然后在控制器中使用:

    public function index()
    {
        $users = User::search()->orderBy('name')->paginate(20);
    
        return view('home', compact('users'));
    }
    

    如果没有搜索参数,此代码将对所有用户进行分页,或者将过滤用户并对其进行分页。

    【讨论】:

    • 您好,我的 html 怎么样?我还需要为 users 添加更多内容吗?因为我修复了所有问题,但搜索栏尚未过滤用户@Alexey Mezenin
    • 应该是@foreach($users as $user)$user-&gt;name$user-&gt;city
    猜你喜欢
    • 2017-05-29
    • 2018-09-24
    • 2020-02-15
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2018-12-14
    相关资源
    最近更新 更多