duanliang1019
2017-05-04 10:58
浏览 794

Laravel检查路由中是否存在给定URL的路由

By providing a URL I would like to know if there's any way to determine if the URL exists in my Laravel application (in comparison to "How can I check if a URL exists via Laravel?" which wants to check an external URL)?

I tried this but it always tells me the URL doesn't match:

$routes = \Route::getRoutes();
$request = \Request::create('/exists');
try {
    $routes->match($request);
    // route exists
} catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e){
    // route doesn't exist
}

图片转代码服务由CSDN问答提供 功能建议

通过提供一个URL我想知道是否有办法确定我的Laravel应用程序中是否存在该URL( 与“如何检查网址是否存在相比较 通过Laravel?“想检查一个外部URL?”

我试过这个,但它总是告诉我URL不匹配: \ n

  $ routes = \ Route :: getRoutes(); 
 $ request = \ Request :: create('/ exists'); 
try {
 $ routes-> match($ request)  ; 
 //路由存在
} catch(\ Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException $ e){
 //路由不存在
} 
   
  
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanlisha2335 2017-05-04 12:41

    In one of my Laravel application, I achieved it by doing the following

    private function getRouteSlugs()
    {
        $slugs  = [];
        $routes = Route::getRoutes();
    
        foreach ($routes as $route)
        {
            $parts = explode('/', $route->uri());
            foreach ($parts as $part)
            {
                $slug    = trim($part, '{}?');
                $slugs[] = $slug;
            }
        }
    
        return array_unique($slugs);
    }
    

    This function would help to get all the slugs that are registered within Laravel and then with a simple in_array you can check if that slug has been reserved.

    EDIT

    Based on your comment, you can extend the following function

    private function getRouteSlugs()
    {
        $slugs  = [];
        $routes = Route::getRoutes();
    
        foreach ($routes as $route)
        {
            $slugs[] = $route->uri();
        }
    
        return array_unique($slugs);
    }
    

    That will get you an array of items as such:

    0 => "dashboard/news"
    1 => "dashboard/post/news"
    2 => "dashboard/post/news/{id}"
    3 => "dashboard/post/news"
    

    It should be easy enough from here to compare.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题