Laravel5 - how to correctly write route for search query string?

Question

I'm working on an app, where I should be performing search on a table containing users. However, I cannot figure out how to correctly compose the route in order to attach the view with the controller and back. My code is the following: The view:

<form action='{{url(' users')}}' method='GET'>
<input class='form-control' type="text" name="keyword" placeholder="Search for user...">
</form>

The route:

Route::get('users?keyword={$keyword}', 'UsersController@search');

The search() in UsersController:

public function search()
{
    $keyword = Request::get('keyword');

    $users = User::where("username", "LIKE","%$keyword%")
            ->orWhere("firstname", "LIKE", "%$keyword%")
            ->orWhere("lastname", "LIKE", "%$keyword%")
            ->orWhere("email", "LIKE", "%$keyword%")
            ->orWhere("phone", "LIKE", "%$keyword%")->get();

    return view('search', compact('users'));

}

Can someone please tell what would be the correct syntax? Thanks in advance!


Show source
| laravel   | php   | mysql   | laravel-5   | search   2016-11-15 20:11 2 Answers

Answers to Laravel5 - how to correctly write route for search query string? ( 2 )

  1. 2016-11-15 20:11

    Your route should be as:

     Route::get('users', 'UsersController@search');
    

    And in your controller, you can get the query parameter by using get function of the request object, which you are doing already.

    You can get the parameter by any of function as:

    request()->get('keyword');
    request()->input('keyword');
    request()->query('keyword');
    

    Update

    Add the following import at the top of your file:

    use Illuminate\Http\Request;
    

    Then in your controller function inject it as:

    public function search(Request $request)
    {
        $keyword = $request->input('keyword');
        // or
        $keyword = $request->query('keyword');
    
        // rest of the code
    }
    
  2. 2016-11-15 20:11

    Try this:

      Route::get('users', 'UsersController@search');
    

    controller

    public function search(Request $request) {
        $keyword = $request->get('keyword');
    
        $users = User::where("username", "LIKE","%$keyword%")
                ->orWhere("firstname", "LIKE", "%$keyword%")
                ->orWhere("lastname", "LIKE", "%$keyword%")
                ->orWhere("email", "LIKE", "%$keyword%")
                ->orWhere("phone", "LIKE", "%$keyword%")->get();
    
        return view('search', compact('users'));
    }
    

Leave a reply to - Laravel5 - how to correctly write route for search query string?

◀ Go back