sklrboy sklrboy - 17 days ago 6
MySQL Question

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

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!

Answer

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
}
Comments