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!
I think there is no optional parameter with nikic/FastRouter.
I dont think ? Means optional with lumen router.
Try with a regular expression {param:(.*)?}
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
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.
We could do it by defining two different route.
- It won't need {param}
$app->get('user/}',[
'as' => 'user',
'uses' => 'App\Http\Controllers\UserController@get'
]);
- 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
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'
]);
I have some problem with Lumen optional parameter
Url : http://<mysite>.com/api/v1/user/
was listing all users then I added option $id as below
$app->get('user[/{id}]','UserController@index');
and now
Would be great if someone can point whats wrong...
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) ?
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
@PRITI - gdecris' answer worked for me in the three cases you have written.
Please or to participate in this conversation.