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.

    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码