Check if route exists in Symfony 4

Viewed 4329

How can I test whether a given route exists in Symfony 4 by using the route name.

routes.yaml

home:
  path: /
  controller: App\Controller\Home::index
  methods: [GET]

login:
  path: /login
  controller: App\Controller\Login::index
  methods: [GET]

Controller (making up an exists() method here)

$routes->exists('home'); // true
$routes->exists('login'); // true
$routes->exists('foo'); // false
1 Answers

From the Symfony 4 Documentation...

Check if a Route Exists

In highly dynamic applications, it may be necessary to check whether a route exists before using it to generate a URL. In those cases, don't use the getRouteCollection() method because that regenerates the routing cache and slows down the application.

Instead, try to generate the URL and catch the RouteNotFoundException thrown when the route doesn't exist:

use Symfony\Component\Routing\Exception\RouteNotFoundException;

// ...

try {
    $url = $generator->generate($dynamicRouteName, $parameters);
} catch (RouteNotFoundException $e) {
    // the route is not defined...
}

You can put that code inside a function and return whatever you need.

Related