php – Search bar in Laravel 5.3 to filter the table-ThrowExceptions

Exception or error:

1) I added the search bar to the 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

2) In 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 }}

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.

How to solve:

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

Your email address will not be published. Required fields are marked *