Home » Php » php – Check url before redirect symfony2

php – Check url before redirect symfony2

Posted by: admin July 12, 2020 Leave a comment

if ($u = $this->generateUrl('_'.$specific.'_thanks'))
  return $this->redirect($u);
  return $this->redirect($this->generateUrl('_thanks'));

I wan’t to redirect to the _specific_thanks url when it exist. So How to check if a url exist?

When I did that, I had this error:

Route “_specific_thanks” does not exist.

How to&Answers:

I don’t think there’s a direct way to check if a route exists. But you can look for route existence through the router service.

$router = $this->container->get('router');

You can then get a route collection and call get() for a given route, which returns null if it doesn’t exist.

$router->getRouteCollection()->get('_'. $specific. '_thanks');


Using getRouteCollection() on runtime is not the correct solution. Executing this method will require the cache to be rebuilt. This means that routing cache will be rebuilt on each request, making your app much slower than needed.

If you want to check whether a route exists or not, use the try … catch construct:

use Symfony\Component\Routing\Exception\RouteNotFoundException;

try {
} catch (RouteNotFoundException $e) {
    dump('Oh noes, route "some_route" doesn't exists!');


Try something like this, check the route exists in the array of all routes:

    $router = $this->get('router');

    if (array_key_exists('_'.$specific.'_thanks',$router->getRouteCollection->all())){
        return $this->redirect($this->generateUrl('_'.$specific.'_thanks'))
    } else {
        return $this->redirect($this->generateUrl('_thanks'));


Did you check your cast?
And are you sure about the route? usually route start with



Try this:

if ($u == $this->generateUrl('_'.$specific.'_thanks') )