Last active
July 23, 2020 23:20
-
-
Save aphoe/26495499a014cd8daf9ac7363aa3b5bd to your computer and use it in GitHub Desktop.
Function to check if a route exists in Laravel 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param $route | |
* @return bool | |
*/ | |
function checkRoute($route) { | |
$routes = \Route::getRoutes()->getRoutes(); | |
foreach($routes as $r){ | |
if($r->getUri() == $route){ | |
return true; | |
} | |
} | |
return false; | |
} |
or
Route::has($route_name);
Thank you so much
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;
}
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
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