David Weng
David Weng

Reputation: 4235

Cakephp Nested Routes

I've got a controller called Items and another one called Categories. Items may belong to different Categories.

The routes that I have are

/items
/items/:item_id
/items/categories
/items/categories/:category_id

And this is my routes.php

Router::connect('/items', array('controller' => 'items', 'action' => 'index');
Router::connect('/items/:item_id', array('controller' => 'items', 'action' => 'view'), array('pass' => array('item_id')), array("item_id" => "[0-9]+"));
Router::connect('/items/categories', array('controller' => 'categories', 'action' => 'index'));
Router::connect('/items/categories/:category_id', array('controller' => 'categories', 'action' => 'view', array('pass' => array('category_id')), array("category_id" => "[0-9]+"));

The problem is that the third route fails as it routes to the Items controller which it shouldn't.

How can I fix this problem?

Upvotes: 0

Views: 1061

Answers (2)

pleasedontbelong
pleasedontbelong

Reputation: 20102

be careful on the order of your routes... cake will match to the first occurrence, so try using your routes like this:

Router::connect('/items', array('controller' => 'items', 'action' => 'index');
Router::connect('/items/categories', array('controller' => 'categories', 'action' => 'index'));
Router::connect('/items/categories/:category_id', array('controller' => 'categories', 'action' => 'view', array('pass' => array('category_id')), array("category_id" => "[0-9]+"));
Router::connect('/items/:item_id', array('controller' => 'items', 'action' => 'view'), array('pass' => array('item_id')), array("item_id" => "[0-9]+"));

good luck

Upvotes: 4

Headshota
Headshota

Reputation: 21449

in you config/routes.php

put a line

Router::connect('/items/categories', array('controller' => 'categories',
 'action' => 'index'));

or something similar.

it will redirect all you /items/categories to the index action of categories controller.

for admin pages (actions that use admin prefix):

Router::connect('/items/categories', array('controller' => 'categories',
 'action' => 'index','admin'=>true));

Upvotes: 1

Related Questions