CodeIgniter Forums

Full Version: How to setup a route for an optional second param?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Do I need to setup two rules in the Routes.php for these two urls?

Code:
1) http://mydomain.example/show-list
2) http://mydomain.example/show-list/25
PHP Code:
Rule 1$routes->add('show-list''Home::index');
Rule 2$routes->add('show-list/(:any)''Home::index'); 
Is there any way to achieve that in on rule? Just trying to avoid having to repeat it.

PHP Code:
//HomeController.php 
public function index()
{
 
$user_id $this->request->uri->getSegment(2);
 if(
$user_id != NULL) {
 
//filter data by given user_id
 
} else {
 
//show all data
 
}
 return 
view('listdata'compact('data');


If I have only this rule
Code:
$routes->add('show-list', 'Home::index');
then it throws 404 file not found for url http://mydomain.example/show-list/25

If I have only this rule
Code:
$routes->add('show-list/(:any)', 'Home::index');
then it throws 404 file not found for url http://mydomain.example/show-list
Have you tried:
$routes->add('show-list/(:any)', 'Home::index'/$1);
Yes I already tried and it throws up error too.

The only way I can get working is by using a regular expression with an optional flag.
Did you try it like this?

According to the doc's the $1 has to go into the quotes.

PHP Code:
$routes->add('show-list/(:any)''Home::index/$1');
// or
$routes->add('show-list/(.+)''Home::index/$1'); 

Not tested.