7
votes

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
    </button>
</span>

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.'%')
        ->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

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

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

1

1 Answers

7
votes

You need to use like instead of =:

$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.