【问题标题】:Laravel How to get Route Profile based on Route NameLaravel 如何根据路由名称获取路由配置文件
【发布时间】:2017-08-22 09:01:00
【问题描述】:

我有这条路线:

Route::get('/test',['as'=>'test','custom_key'=>'custom_value','uses'=>'TestController@index'])

我已经尝试使用$routeProfile=route('test'); 但是结果返回的是urlstring http://domain.app/test

我需要['as'=>'test','custom_key'=>'custom_value'],这样我才能得到$routeProfile['custom_key']

如何根据路由名称获取“custom_value”?

【问题讨论】:

  • 这里的custom_key是什么意思?
  • 嗨@AddWebSolutionPvtLtd,我手动添加它,就像路由配置文件的一些标记一样。也许我可以为菜单层次结构添加“描述”或“父级”或“is_displayed”。
  • 我添加了两种不同的答案,您可以根据需要选择。

标签: laravel routing routes laravel-5.4 router


【解决方案1】:

为了最快的方式,现在我用这个来回答我的问题:

function routeProfile($routeName)
{
    $routes = Route::getRoutes();
    foreach ($routes as $route) {
        $action = $route->getAction();
        if (!empty($action['as']) && $routeName == $action['as']) {
            $action['methods'] = $route->methods();
            $action['parameters'] = $route->parameters();
            $action['parametersNames'] = $route->parametersNames();
            return $action;
        }
    }
}

如果有更好的答案,我将不胜感激。 谢谢...

【讨论】:

  • 不过,没有比这更好的方法了。 +1 点赞
【解决方案2】:

试试这个:

use Illuminate\Support\Facades\Route;

$customKey = Route::current()->getAction()['custom_key'];

【讨论】:

    【解决方案3】:

    我相信您正在寻找一种将变量传递给您的路线的方法

    Route::get('/test/{custom_key}',[
        'uses'=>'TestController@index',
        'as'=>'test'
    ]);
    

    您可以像这样使用 route('test',['custom_key'=>'custom_key_vale'])

    在你看来:

    <a href="{route('test',['custom_key'=>'custom_key_vale'])}"
    

    在你的控制器方法中:

    ....
    
    public function test(Request $request)
    {
       $custom_key = $request->custom_key;
    }
    ....
    

    【讨论】:

      【解决方案4】:

      您可以尝试以下代码之一:
      1.在命名空间行代码后添加use Illuminate\Http\Request;

      public function welcome(Request $request)
      {
          $request->route()->getAction()['custom_key'];
      }
      

      2。或带有门面

      namespace 行代码之后添加use Route;

      并在您的方法中使用以下内容

      public function welcome()
      {
          Route::getCurrentRoute()->getAction()['custom_key'];
      }
      

      两者都经过测试并且工作正常!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-04
        • 1970-01-01
        • 2018-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-15
        • 1970-01-01
        相关资源
        最近更新 更多