Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect if route does'n exist

Tags:

php

symfony

I have a question : so for examples I have an app in symfony3 which have the following routes : /admin/login,admin/news,admin/gallery, but the route /admin/authentification doesn't exist. So the idea is if the route doesn't exist I want to redirect the user to homepage /. Can you help me please ? Thanks in advance and sorry for my english

like image 284
Harea Costicla Avatar asked Mar 14 '26 07:03

Harea Costicla


1 Answers

I'm not confident this is the best solution, but you can use a UrlMatcher to check that the URL you're passing correlates to an available route:

/**
 * @Route("/debug")
 */

public function DebugAction(){
    $router = $this->get('router');

    //Get all the routes that exist.
    $routes = $router->getRouteCollection();
    $context = $router->getContext();

    $urlMatcher = new UrlMatcher($routes, $context);

    $url = '/admin/login';
    try{
        //UrlMatcher::match() will throw a ResourceNotFoundException if the route 
        //doesn't exist.
        $urlMatcher->match($url);
        return $this->redirect($url);
    } catch (\Symfony\Component\Routing\Exception\ResourceNotFoundException $e){
        return $this->redirect('/');
    }
}

I'm not particularly keen on this solution because it relies on catching an exception, rather than checking a boolean value to determine if the route exists.

like image 81
HPierce Avatar answered Mar 15 '26 20:03

HPierce