verdond2 verdond2 - 1 month ago 16
PHP Question

Optional Parameter Index Route

I'm looking to have an optional parameter on the index route like so:

$app->get('/{name?}', function ($name) {
//Do Something here
});


I basically want to check and see if there is a parameter supplied. If so return a specific view, if not return the standard index view. For the life of me I can't get it to work, more than likely doing something stupid! Any help would be greatly appreciated!

Answer

First of all, you need to make the $name argument optional in your controller function so that it works when name is niot provided. Then, based on whether the parameter is set or not, you could return different views:

$app->get('/{name?}', function ($name = null) {
  if (is_null($name))  {
    return view('index');
  }
  else {
    return view('some_other_view');
  }
});

NOTE: In my opinion it would be more readable if you created 2 separate routes, one for index and one that takes the name parameter, as behaviour of your application in those 2 cases seems to be completely different.