0
votes

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 www.example.com/pages/product/ID.

I want to setup a custom route so I can access the product by going to 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.

1

1 Answers

1
votes

You don't need 2 additional segments. One should be sufficient.

$route['PRODUCT_NAME/PRODUCT_ID'] = 'pages/product/PRODUCT_ID';

However, if I were you I would make the URL to have the first segment to be the id of the product instead.

$route['PRODUCT_ID/PRODUCT_NAME'] = 'pages/product/PRODUCT_ID';

That way, if I only know the product id, I wouldn't have to type example.com//123 which might cause some problem. If I'm not mistaken, if you do that, CI will try to load a controller named 123.