Search bar in Laravel 5.3 to filter the table


First) added the search bar 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

Second) my Controller I'm displaying all my users in a 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.'%')

    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>


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

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

how can I achive that ? sorry for the long question in advance.

Show source
| laravel   | php   | html   | blade   | search   2016-12-07 11:12 1 Answers

Answers to Search bar in Laravel 5.3 to filter the table ( 1 )

  1. 2016-12-07 11:12

    You need to use like instead of =:

    $users = User::where('name', 'like', '%'.$search.'%')

    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.

Leave a reply to - Search bar in Laravel 5.3 to filter the table

◀ Go back