Welcome Guest, Not a member yet? Register   Sign In
Putting (hardcoded) ids in routes

(This post was last modified: 03-14-2019, 01:18 PM by WhiteListed.)

In the tutorial, in the Routing section (https://codeigniter4.github.io/userguide...uting.html), the following code is used to map a route 'blog/joe' to a hardcoded id 34.

PHP Code:

I want to do something similiar, mapping page slugs to my Page controller with a certain id. I am using the following code to do this, where $page is the page variable.

PHP Code:
$routes->get$page->slug'Pages::id/' $page->id ); 

I can't get this to work. When I visit localhost:8080/my-page-slug I get a 404-error, saying Controller method is not found: id\123.

Am I doing something wrong with the mapping? Because if I visit localhost:8080/pages/id/123 it does work as expected.

I was wondering if it would be a problem if I add multiple slashes to the slug, for example, "/parent/child". However, I don't think that that is the problem since the error message seems to indicate that the mapping at least partially succeeded.

I hope someone can explain me what I am doing wrong or at least verify that I am not the only one that is having a problem with this.

OK, seems that I found the cause. In checkRoutes() in codeigniter4->framework->system->Router->Router.php the following code replaces all slashes with backslashes (lines 471 to 474).
PHP Code:
elseif (strpos($val'/') !== false)
$val str_replace('/''\\'$val);

Does anybody now why this code is there? As in: why should all slashes be translated to backslashes when they are also used for adding parameters to the routes...? Anyways, commenting these for lines of code prevents the uri from being translated to id\123 and ensures that I can access the page with id 123 at the page_slug.

It would be great if anybody could explain why this code is necessary and if I am doing something wrong with my routing that gives me these issues.

I had a quick look into this and it seems that CodeIgniter does something weird with the routing here. For some reason the url is not divided into segments correctly (because the / gets translated into a \ somewhere). Then the

PHP Code:
$segments explode('/'$uri); 

in the autoRoute function does not divide the URI into the correct segments. Which in turn leads to CodeIgniter trying to find the method "id\123" in the Pages controller, which of course does not exist. If I have some time this evening I will try to find out why the / in the $uri gets translated into a \.

I'll get back when I have some more information to share. In the meantime, I still hope that someone can verify that this is not only happening on my machine (or can point my in the direction of where to fix this bug Cool ).

not sure, but maybe this helps : https://github.com/codeigniter4/CodeIgni...ssues/1838

Thanks, for sharing the tutorial.

Theme © iAndrew 2016 - Forum software by © MyBB