tags:

views:

105

answers:

1

Is there any way to route urls in cake without having the ID in the url?

So instead of www.mydomain.com/id/article-name I just want www.mydomain.com/article-name

I've been following this. http://book.cakephp.org/view/543/Passing-parameters-to-action

+5  A: 

Sure. The only requirement for this is that there's enough unique information in the URL to pin down the article you want. If /article-name is unique in your database, you can use it to find the specific record you want.

In config/routes.php:

// ... configure all normal routes first ...

Router::connect('/*', array('controller' => 'articles', 'action' => 'view'));

In controllers/articles_controller.php:

function view ($article_name) {
    $article = $this->Article->find('first', array(
        'conditions' => array('Article.name' => $article_name)
    ));
    ...
}

Be careful not to name your products like anything that could legitimately appear in the URL, so you don't run into conflicts. Does the URL http://example.com/pages point to the product 'pages' or to array('controller' => 'pages', 'action' => 'index')? For this purpose you'll also need to define your routes in routes.php in a way that allows all your controllers to be accessible first, and only the undefined rest gets piped into your ArticlesController. Look at the third parameter of Routes::connect, which allows you to specify a RegEx filter you could use for this purpose.

deceze