Hi everyone,
I’ve encountered an issue with routing and I’m not sure whether it’s a bug or expected behavior not clearly explained in the documentation.
I like to handle form processing in the same method that renders the form’s HTML. Additionally, I prefer using optional IDs in these methods:
- When there’s no ID, it handles entity creation.
- When there is an ID, it handles entity editing.
I’ve seen this approach in various projects and find it quite intuitive.
Now, I want to create a method for editing a post with an optional ID. From what I understand, the only way to achieve this is by defining two routes:
PHP Code:
$routes->match(['GET', 'POST'], 'edit', 'PostController::edit');
$routes->match(['GET', 'POST'], 'edit/(:num)', 'PostController::edit/$1');
However, if I want to assign a name to one of these routes, I can only name the route without the ID:
PHP Code:
$routes->match(['GET', 'POST'], 'edit', 'PostController::edit', ['as' => 'edit']);
$routes->match(['GET', 'POST'], 'edit/(:num)', 'PostController::edit/$1');
If I try to name the route with the ID instead, navigating to it returns a 404 error:
PHP Code:
$routes->match(['GET', 'POST'], 'edit', 'PostController::edit');
$routes->match(['GET', 'POST'], 'edit/(:num)', 'PostController::edit/$1', ['as' => 'edit']);
For example, navigating to
/edit/12 results in a 404.
Is this behavior intentional? Or am I missing something in the way named routes and optional parameters are meant to work in CodeIgniter 4? Any guidance would be appreciated.
Thanks in advance!