Cameron
Cameron

Reputation: 28783

Routing not working when using dash in the url

I have the following two routes in my app:

Router::connect('/posts/:id',
                    array('controller' => 'posts', 'action' => 'view'),
                    array('id' => '[A-Za-z0-9\._-]+', 'pass' => array('id')));

    Router::connect('/posts/:slug-:id',
                    array('controller' => 'posts', 'action' => 'view'),
                    array(
                        'id'   => '[A-Za-z0-9\._-]+',
                        'slug' => '[A-Za-z0-9\._-]+',
                        'pass' => array('id', 'slug')
                    ));

and an example url would be:

/posts/This_is_the_first_post-1

However it would show a 404 but if I change the url - before the id to a / it will work :/ Any ideas what the issue is? Is the regex causing it??

Here is my method for the view:

function view ( $id = null, $slug = null )
    {
        $post = $this->Post->find('first',array('contain'=>array('User'=>'Profile'),'conditions'=>array('Post.id'=>$id)));

        if (!$post)
        {
            throw new NotFoundException('404');
        }
        else if($post['Post']['status'] == '0') // 0=draft 1=closed 2=open
        {
            if($post['Post']['user_id'] == $this->Auth->user('id'))
            {
                $this->Session->setFlash('Your post has NOT been published yet');
            }
            else
            {
                throw new NotFoundException('404');
            }
        }

        if (Inflector::slug($post['Post']['title']) != $slug || $slug = null)
        {
            $this->redirect(array('id'=>$post['Post']['id'],'slug'=>Inflector::slug($post['Post']['title'])));
        }

        $this->set(compact('post'));
    }

Upvotes: 2

Views: 1000

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270609

It looks to be caused by the regular expressions. In the first route, you're allowing -, so it may not distinguish itself from the second route, where :id is supposed to follow a -.

Router::connect('/posts/:id',
                array('controller' => 'posts', 'action' => 'view'),
                array('id' => '[A-Za-z0-9\._]+', 'pass' => array('id')));
                //---Removed hyphen-----^^^^^^

Router::connect('/posts/:slug-:id',
                array('controller' => 'posts', 'action' => 'view'),
                array(
                    'id'   => '[A-Za-z0-9\._]+',
                //---Removed hyphen-----^^^^^^
                    'slug' => '[A-Za-z0-9\._]+',
                //---Removed hyphen-----^^^^^^
                    'pass' => array('id', 'slug')
                ));

Upvotes: 2

Related Questions