user1692333
user1692333

Reputation: 2597

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.

Upvotes: 0

Views: 458

Answers (2)

ArjanSchouten
ArjanSchouten

Reputation: 1368

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');

Upvotes: 1

Pᴇʜ
Pᴇʜ

Reputation: 57683

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');

Upvotes: 0

Related Questions