Check If Route Exists in Symfony 7

Check If Route Exists in Symfony 7

When implementing a web application, we may need to check whether a route exists. This tutorial provides example how to do it in Symfony 7 application.

We can inject the UrlGeneratorInterface dependency in a controller or service to generate a URL or path for a given route name. The generate method throws RouteNotFoundException if a route not exists. We can catch this exception and perform appropriate action.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class TestController
{
    #[Route('/')]
    public function index(UrlGeneratorInterface $urlGenerator): Response
    {
        try {
            $url = $urlGenerator->generate('wrong');
        } catch (RouteNotFoundException) {
            return new Response('Route not exists');
        }

        return new Response($url);
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.