Skip to content

Instantly share code, notes, and snippets.

@aphoe
Last active July 23, 2020 23:20
Show Gist options
  • Save aphoe/26495499a014cd8daf9ac7363aa3b5bd to your computer and use it in GitHub Desktop.
Save aphoe/26495499a014cd8daf9ac7363aa3b5bd to your computer and use it in GitHub Desktop.
Function to check if a route exists in Laravel 5
/**
* @param $route
* @return bool
*/
function checkRoute($route) {
$routes = \Route::getRoutes()->getRoutes();
foreach($routes as $r){
if($r->getUri() == $route){
return true;
}
}
return false;
}
@aphoe
Copy link
Author

aphoe commented Nov 5, 2016

You can put this in a helper file.

Check my blog post on how to create custom helper function files in Laravel 5, if you need to

@SOSTheBlack
Copy link

SOSTheBlack commented Dec 28, 2017

or

Route::has($route_name);

@MichaelAndish
Copy link

Thank you so much

@rpounder
Copy link

rpounder commented Apr 26, 2019

updated;

     * @param $route
     *
     * @return bool
     */
    function checkRoute($route)
    {
        if($route[0] === "/"){
            $route = substr($route, 1);
        }
        $routes = \Route::getRoutes()->getRoutes();
        foreach ($routes as $r) {
            /** @var \Route $r */
            if ($r->uri == $route) {
                return true;
            }
        }

        return false;
    }

@akatukima
Copy link

akatukima commented Apr 12, 2020

If you also want to check named routes


    /**
     * @param $route
     * @return bool
     */
    function checkRoute($route)
    {
        if($route[0] === "/"){
            $route = substr($route, 1);
        }
        $routes = \Route::getRoutes()->getRoutes();
        foreach ($routes as $r) {
            /** @var \Route $r */
            if ($r->uri == $route) {
                return true;
            }
            if (isset($r->action['as'])) {
                if ($r->action['as'] == $route) {
                    return true;
                }
            }
        }

        return false;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment