简体   繁体   中英

How to use optional values in Laravel routes?

I have the following route:

Route::get('users/search/{type?}/{value}', 'Site\UserController@search');

The main idea is to simplify the search:

if type exists (name, surname, email and etc.) search only by that field.
if not - search everywhere.

But when I do:

http://example.com/users/search/sdgfdfxg 

Laravel throws

Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException 

With

http://example.com/users/search/name/sdgfdfxg

or

http://example.com/users/search/surname/sdgfdfxg

everything is fine.

Yust define 2 routes:

Route::get('users/search/{type}/{value}',function($type,$value){
    $app = app();
    $controller = $app->make('Site\UserController');
    $controller->callAction($app, $app['router'], 'search', $parameters = array($type,$value));
});
Route::get('users/search/{value}',function($value){
    $app = app();
    $controller = $app->make('Site\UserController');
    $controller->callAction($app, $app['router'], 'search', $parameters = array(null,$value));
});

But still the easiest option is to change the order of defining you're parameters. Set the optional option to the end of the url:

Route::get('users/search/{value}/{type?}','Site\UserController@search');

You could register 2 routes. One with 'type' and one without to handle both cases.

Route::get('users/search/{type}/{value}', 'Site\UserController@searchByType');
Route::get('users/search/{value}', 'Site\UserController@search');

First, you can never make an optional parameter the first. Optional parameters always are the last ones in a function or URL.

According to the docs, you have to put a question mark next to it, like this:

Route::get('users/search/{value}/{type?}', 'Site\UserController@search');

And in your search function:

public function search($value, $type = null) {
    // Handle your code here...
}

I know it seems weird to have an URL with a value first, and then the type... If you're bothered by that, I suggest you use the answer from Peh.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM