![]() |
optional parameters in route definition - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24) +--- Thread: optional parameters in route definition (/showthread.php?tid=88365) |
optional parameters in route definition - Dimtrovich - 08-29-2023 Hello everyone. I am trying to create a route with 2 parameters. The first being mandatory and the second being optional. I've gone through all the documentation but I don't see any section that talks about this. So my question is how to do it. For the moment I had to create 2 routes PHP Code: $routes->addPlaceholder([ But I would like to have only one route like: PHP Code: $routes->get('docs/(:version)/(:page)?', [DocsController::class, 'show']); So far it doesn't seem to exist ![]() RE: optional parameters in route definition - davis.lasis - 08-29-2023 I would manage like this routes.php PHP Code: $routes->get('docs/(:any)/(:any)', 'DocsController::show/$1/$2'); Controller method PHP Code: public function show(string $version, string $page = '') RE: optional parameters in route definition - kenjis - 08-29-2023 Yes, there is no optional parameters. RE: optional parameters in route definition - Dimtrovich - 08-30-2023 (08-29-2023, 10:27 AM)davis.lasis Wrote: I would manage like this Indeed, it is a good alternative. The problem I have with this is that by using the *any* placeholder, any string will be allowed in the URL and therefore can possibly generate an error at the controller level. Unless I first test the parameters received by my controller method before really starting my business logic. I will keep the use of 2 routes, knowing that the 2nd parameter of my controller method is optional. There at least I know that the URL verification will be managed by CodeIgniter. PS: In general, I am very restrictive, I prefer to define strong routing (without the auto router and using strict regex) (08-29-2023, 08:55 PM)kenjis Wrote: Yes, there is no optional parameters.Don't you think it would be interesting to have it? There are multiple use cases that may require it. The solution could be using the AutoRouter or using the "_remap" method but having strict defined routes is more secure in my opinion |