Define Route With Priority in Symfony 7

Define Route With Priority in Symfony 7

There might be a case when two or more routes can match the same URL. In Symfony, application routes are evaluated in the order they are defined. Routes that defined in the YAML file can be moved up or down for controlling route priority. It is much harder to do if routes are defined using PHP attributes.

This tutorial shows example how to define route with priority in Symfony 7 application.

When routes are defined using PHP attributes, the priority parameter can be used to define the route priority. The priority parameter is an integer value which can be a positive or negative. The higher value means that route has more priority. Default value is 0. The priority parameter can be used only with PHP attributes.

Let's say we have the following controller:



namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class PostController
    #[Route('/post/{slug}', name: 'post_view')]
    public function view(string $slug): Response
        return new Response('Slug: '.$slug);

    #[Route('/post/list', name: 'post_list', priority: 1)]
    public function list(): Response
        return new Response('A list of posts');

If the URL path is /list, then both routes can match it. Symfony will match the route post_list because it has higher priority (it is 1) than route post_view (priority is 0).

Leave a Comment

Cancel reply

Your email address will not be published.