jcalonso's avatar

Lumen - Route with optional parameters

Hello,

I'm starting new app with Lumen and I'm trying to create a route with optional parameters like this:

$app->get('user/{param?}',[
    'as'   => 'user',
    'uses' => 'App\Http\Controllers\UserController@get'
]);

And the controller:

public function get($param = null)
    {
    ...
    }

If I hit the url http://myApp.dev/user/ I get a 404

if I hit http://myApp.dev/user/something It get routed but the $param variable is null.

I was looking at nikic/FastRouter (lumen router) and I couldn't find any support for optional parameters.

Am I missing something, or there is no support for optional parameters?

Thanks!

0 likes
10 replies
bestmomo's avatar
Level 52

I think there is no optional parameter with nikic/FastRouter.

2 likes
pmall's avatar

I dont think ? Means optional with lumen router.

Try with a regular expression {param:(.*)?}

jcalonso's avatar

Hi again

@bestmomo true @pmall doesn seem to work either

Even normal url parameters aren't supported if I add a ?someParam=someValue the route wont match and will return 404

pmall's avatar

Even normal url parameters aren't supported if I add a ?someParam=someValue the route wont match and will return 404

Are you sure you removed the {param?} part for this case ? It seems like the way to handle this.

mayurvandra's avatar

We could do it by defining two different route.

  1. It won't need {param}

$app->get('user/}',[
    'as'   => 'user',
    'uses' => 'App\Http\Controllers\UserController@get'
]);

  1. It will need {param}

$app->get('user/{param}',[
    'as'   => 'user',
    'uses' => 'App\Http\Controllers\UserController@get'
]);

There won't be a support for optional route parameter in Lumen. Check out Github Thread: https://github.com/laravel/lumen-framework/issues/99

2 likes
gdecris's avatar

Lumen uses fast route and in there documentation it says to do the following for optional parameters...

$app->get('user[/{param}]',  [
    'as'   => 'user',
    'uses' => 'App\Http\Controllers\UserController@get'
]);
12 likes
am05mhz's avatar

gdecris's answer should be the best answer, it does exactly as intended, optional parameters.

$app->get('user[/{param}]' ...

@priti do your UserController@index have default value? such as function index($id = null) ?

thiagonatanael's avatar

For those who have this question, we can nest optional parameters like so:

$app->get('all[/[{user_id}]]', 'UserController@getAll');

This will work for all of those routes:

../all

../all/

../all/123

1 like
lucasctd's avatar

@PRITI - gdecris' answer worked for me in the three cases you have written.

Please or to participate in this conversation.