CodeIgniter Forums
How to setup a route for an optional second param? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How to setup a route for an optional second param? (/showthread.php?tid=73026)



How to setup a route for an optional second param? - happyape - 03-11-2019

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


RE: How to setup a route for an optional second param? - devops - 03-13-2019

Have you tried:
$routes->add('show-list/(:any)', 'Home::index'/$1);


RE: How to setup a route for an optional second param? - happyape - 03-18-2019

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.


RE: How to setup a route for an optional second param? - InsiteFX - 03-18-2019

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.