Search code examples
symfonyslug

Slugs causing route conflicts


I have an action in my PostController that is displaying all the posts on the main page having a slug as an argument.

PostController:displayAction

/**
 * @Route("/{postSlug}", defaults={"postSlug"= false})
 * @Template()
 */
 public function displayAction($postSlug)
 {
     //Forget about whats inside here
     return array[];
 }

Now i have another controller for Users having a login action and for that i am setting /login as route in Route annotation

UserController:loginAction

/**
 * @Route("/login")
 * @Template()
 */
public function loginAction()
{
    //bla bla bla
    return [];
}

Now the issue is that when ever i try to access localhost:8000/login, it shows me a white page and the controller and action on the debug tool bar is PostController:DisplayAction where as it should be UserController::loginAction. The reason i believe is that it is causing some conflicts with the slug but i can defend my stance here by saying that i have another controller "CreatePostController" having Route annotation "/create" which works fine, i am not sure why but it works.

I am sure i am doing some mistake but do not know what and if there is a conflict then how can CreatePostController work?

Router:Debug Screenshot Router:Debug

Routing.yml

blogger_blog_homepage:
resource: "@BloggerBlogBundle/Controller"
type: annotation

Solution

  • Problem is with routing. If you have route declaration for /{postSlug} before /login route, then it will access /{postSlug} before /login, because login is matching postSlug too. System doesn't know that login is not postSlug.

    You can avoid that by putting /login route before /{postSlug} route. Check your routing.yml file.

    Because you are using annotation for routing, you have to be carefull, because Symfony uses some priorities.

    Break down your routing.yml into:

    blogger_blog_user:
    resource: "@BloggerBlogBundle/Controller/UserController.php"
    type:     annotation
    
    blogger_blog_homepage:
    resource: "@BloggerBlogBundle/Controller/PostController.php"
    type:     annotation
    

    And the same for CreatePostController. UserController must be before other controllers.