Search bar in Laravel 5.3 to filter a table

First) a search bar has been added to view:

{!! 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>

Second) my controller I show all my users in the table, and the search bar is on top of it

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 such a loop @foreach ($ users as $ user) {{$ user-> name}} @endforeach and replace the view only with the names found. and here is the route for the index

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

how can i achieve this Sorry for the long question in advance.

+4
source share
1 answer

You need to use likeinstead =:

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

, . - :

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

, , .

+7

Source: https://habr.com/ru/post/1663074/


All Articles