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

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
}
  • 写回答

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.

    评论

报告相同问题?

悬赏问题

  • ¥20 求计算赫斯特(Hurst)指数
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大