I’m having an issue with routing in codeigniter.
Lets say I have a controller named Pages, with a method named product that does the following:
public function product() {
$this->load->model('pages_model');
$productid = $this->uri->segment(3);
$data['product'] = $this->pages_model->getProduct($productid);
// ...load view, etc.
}
To access a particular product, my url will be http://www.example.com/pages/product/ID.
I want to setup a custom route so I can access the product by going to http://www.example.com/name-of-product.
However, putting
$route['name-of-product'] = 'pages/product/ID';
does not work. It will load the product view, but the product data will not be loaded. If I say
$route['name-of-product/:any/ID'] = 'pages/product/ID';
it works as it should, but I would rather not have the two additional segments at the end of the url.
You don’t need 2 additional segments. One should be sufficient.
However, if I were you I would make the URL to have the first segment to be the id of the product instead.
That way, if I only know the product id, I wouldn’t have to type
example.com//123which might cause some problem. If I’m not mistaken, if you do that, CI will try to load a controller named123.