1

I'm trying to do the same as this site, stackoverflow, do with their URLs.

CakePHP works like this: website/controller/action/

I want to config routing to achieve this:

myWebSite.com/questions/(question_id)/(question)/

eg: myWebSite.com/questions/12874722/cakephp-routing-controller-alias /

I didnt figured it out how to do this bold part of URL.

tereško
  • 58,060
  • 25
  • 98
  • 150
user1148875
  • 449
  • 4
  • 11
  • 24
  • What does this have to do with "_controller aliases_"? The bold part is the slugged question title. And what exactly is the actual problem? Have you read [**the docs**](http://book.cakephp.org/2.0/en/development/routing.html#passing-parameters-to-action)? ps, please always mention your exact CakePHP version and tag your question accordingly. – ndm Oct 20 '14 at 13:18
  • 2
    Notice that SO actually ignores the question title and you can put [whatever you like](http://stackoverflow.com/questions/26466567/this-is-a-silly-url) in there, but it will redirect if you get it wrong (it's the question ID that is important) – DavidG Oct 20 '14 at 13:20
  • The actual problem is that i don't know how to put it there, the question title in URL. – user1148875 Oct 20 '14 at 13:23
  • 1
    There are sluggable behaviour check them, also save the slug to your database to redirect user to proper url just like S.O. as mentioned by @DavidG – Abhishek Oct 20 '14 at 13:38
  • 1
    @DavidG A common pattern among websites. Redirect on `(SLUG != URI_SEGMENT[N])` – Ryan Oct 20 '14 at 20:39
  • @self Indeed, one I've used myself too. – DavidG Oct 20 '14 at 21:22

1 Answers1

1

In your Config/routes.php

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

In Controller/QuestionsController.php

view action get question id as

public function view() {
    $question_id = isset($this->request->params['pass'][0]) ? $this->request->params['pass'][0] : "";
    $question = isset($this->request->params['pass'][1]) ? $this->request->params['pass'][1] : "";

    if( empty($question_id) ) {
        throw new NotFoundException('Could not find that question');
    }

    // if $question is empty then get slug from database and redirect to /question_id/question


    // Get question details and set
}
Subodh Ghulaxe
  • 18,333
  • 14
  • 83
  • 102