Laravel 5.1 Routes that have question mark

Abdullah picture Abdullah · Nov 13, 2015 · Viewed 8k times · Source

I'm trying to create a route in Laravel 5.1 that will search the records base on "keyword". I like to include a ? in my url for more readability. The problem is that when I'm including the ? and test the route with postman it returns nothing. But when I remove the ? and replaced it with / and test it with postman again it will return the value of keyword. Does Laravel route supports ??

//Routes.php
Route::get('/search?keyword={keyword}', [
    'as' => 'getAllSearchPublications', 
    'uses' => 'PublicationController@index'
]);

//Publication Controller
public function index($keyword)
{
    return $keyword;
}

I've been searching the internet for hours now and I've read the Laravel documentation, But I can't find the answer. Thank you.

Answer

Thomas Kim picture Thomas Kim · Nov 13, 2015

I believe you are talking about query strings. To accept query parameters, you don't pass it as an argument. So, for example, your route should look more plain like this:

Route::get('/search', [
    'as' => 'getAllSearchPublications', 
    'uses' => 'PublicationController@index'
]);

Note: I dropped ?keyword={keyword}.

Then, in your controller method, you can grab the query parameter by calling the query method on your Request object.

public function index(Request $request)
{
    return $request->query('keyword');
}

If you didn't already, you will need to import use Illuminate\Http\Request; to use the Request class.