CakePHP - How to make routes with custom parameters?

14,139

You'll want to use named parameters. For an example from one of my projects

Router::connect('/:type/:slug', 
        array('controller' => 'catalogs', 'action' => 'view'), 
        array(
            'type' => '(type|compare)', // regex to match correct tokens
            'slug' => '[a-z0-9-]+', // regex again to ensure a valid slug or 404
            'pass' => array(
                'slug', // I just want to pass through slug to my controller
            )
        ));

Then, in my view I can make a link which will pass the slug through.

echo $this->Html->link('My Link', array('controller' => 'catalogs', 'action' => 'view', 'type' => $catalog['CatalogType']['slug'], 'slug' => $catalog['Catalog']['slug']));

My controller action looks like this,

public function view($slug) {
    // etc
}
Share:
14,139
BadHorsie
Author by

BadHorsie

Updated on June 05, 2022

Comments

  • BadHorsie
    BadHorsie almost 2 years

    My Cake URL is like this:

    $token = '9KJHF8k104ZX43';
    
    $url = array(
        'controller' => 'users',
        'action' => 'password_reset',
        'prefix' => 'admin',
        'admin' => true,
        $token
    )
    

    I would like this to route to a prettier URL like:

    /admin/password-reset/9KJHF8k104ZX43
    

    However, I would like the token at the end to be optional, so that in the event that someone doesn't provide a token it is still routed to:

    /admin/password-reset
    

    So that I can catch this case and redirect to another page or display a message.

    I've read the book on routing a lot and I still don't feel like it explains the complex cases properly in a way that I fully understand, so I don't really know where to go with this. Something like:

    Router::connect('/admin/password-reset/:token', array('controller' => 'users', 'action' => 'password_reset', 'prefix' => 'admin', 'admin' => true));
    

    I don't really know how to optionally catch the token and pass it to the URL.

  • BadHorsie
    BadHorsie almost 11 years
    Do you have to use named parameters or is there no way to catch the parameters if they don't have associated keys? This looks like it would work even if you didn't have named parameters.
  • BadHorsie
    BadHorsie almost 11 years
    OK, I figured it out. You have to list the parameter as named in your link but it doesn't come through named in the URL.