Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 Routes that have question mark

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.

like image 731
Abdullah Avatar asked Nov 13 '15 04:11

Abdullah


People also ask

How many types of routes are there in Laravel?

Route Parameters Laravel provides two ways of capturing the passed parameter: Required parameter. Optional Parameter.

What are the default route files in Laravel?

The Default Route Files The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.

Which types of route model binding are supported in Laravel?

Laravel currently supports two types of route model bindings. We have: Implicit model binding. explicit model binding.


1 Answers

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.

like image 144
Thomas Kim Avatar answered Oct 10 '22 20:10

Thomas Kim