Leo Galleguillos
Leo Galleguillos

Reputation: 2730

CakePHP - Redirect to controller without action and without slug

Using CakePHP, I would like to redirect from this URL:

http://www.example.com/songs/12345/Michael-Jackson-Billie-Jean

to this URL:

http://www.example.com/songs/12345

In the new URL, the controller is songs, the id is 12345, the implied action is view, and the slug (Michael-Jackson-Billie-Jean) is removed.

Is it possible to program this redirect using the routes config file, or will I need to program a slightly more advanced redirect in either a controller or route class?

I have tried the following two possibilities to no avail. In this first attempt, I end up getting a URL with view in the URL and parameters appended to the end of the URL:

Router::redirect(
    '/songs/:id/**',
    array('controller' => 'songs', 'action' => 'view'),
    array('persist' => array('id'))
);
// Redirects to http://www.example.com/songs/view/Michael-Jackson-Billie-Jean%2Fid%3A1286072880/id:view

In my second attempt, the redirect almost works, but the string :id is literally echoed in the URL:

Router::redirect(
    '/songs/:id/**',
    '/songs/:id'
);
// Redirects to http://www.example.com/songs/:id

I suppose I could write this redirect in the root .htaccess file, but I would prefer to keep all the routing in one place; namely, the CakePHP routes file.

Does anyone know how I can redirect to http://www.example.com/songs/:id where :id is the song ID and not literally the string :id? Thank you so much.

Upvotes: 0

Views: 1153

Answers (1)

Anubhav
Anubhav

Reputation: 1625

Use below route for the simple solution:

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

function view($id=null){   

         // $id will be song id
         // For example, http://www.example.com/songs/12345 here $id is 12345

}

Do not use .htaccess, it will be handled easily from routes.php.

Cheers

Upvotes: 1

Related Questions