【问题标题】:how to get dynamic route prefix如何获取动态路由前缀
【发布时间】:2019-12-11 06:09:53
【问题描述】:

我正在尝试使用中间件创建动态路由前缀。

我在我的web.php 中尝试过这样的:

Route::group(['prefix' => '{role}', 'middleware'=>'operator'], function() {
    Route::get('/whatever', function() {
        dd('halo');
    });
});

我的运营商中间件:

public function handle($request, Closure $next)
{
    dd(Route::current()->uri());
}

但是当我点击/Admin/whatever 时,dd 的输出是这样的"{role}/whatever"。应该是Admin/whatever 对吧?

所以想法是,当我以管理员身份登录时,我想像这样重定向/Admin/home

编辑: 我也在运营商中间件中试过这个:

public function handle($request, Closure $next, $role)
{
    dd($role));
}

但是给我错误太少的参数来函数...

【问题讨论】:

  • 请试试这个兄弟。 Route::group(['prefix' => '{role}', 'middleware'=>'operator'], function() { Route::get('/whatever', function($role) { dd('halo'); }); }); 我没有测试过。但它应该这样做。
  • 请注意前缀希望您静态定义它,而不是从 URL 获取它
  • 感谢您的回复,它仍然是{role}/whatever...

标签: laravel routes middleware


【解决方案1】:

中间件无法使用数据,因为它是在生命周期的早期启动的。会话数据不可用,并且在运行中间件之前似乎还没有完全形成路由。不过,您可以使用另一种方法来返回传递给路由的参数。

\Route::getCurrentRoute()->parameters$request->route()->parameters,随你喜欢。

这将为您提供所有参数的列表,如{key} => value 对所以

\Route::getCurrentRoute()->parameters['role']$request->route()->parameters['role']

应该给你你正在寻找的东西。

【讨论】:

  • 会话数据可能可用,这取决于您在 Http/Kernel.php 中定义中间件的位置
【解决方案2】:

您可以使用以下方法检索您的参数:

\Illuminate\Support\Facades\Route::current()->role;

或更好:

\Illuminate\Support\Facades\Route::current()->parameter('role');

如果您转储 Route::current() 的内容,您将看到您实际拥有的对象:

dump(Route::current());

结果:

Route {#330 ▼
  +uri: "{role}/whatever"
  +methods: array:2 [▶]
  +action: array:5 [▶]
  +isFallback: false
  +controller: null
  +defaults: []
  +wheres: array:3 [▶]
  +parameters: array:1 [▶]
  +parameterNames: array:1 [▶]
  #originalParameters: array:1 [▶]
  +computedMiddleware: array:2 [▶]
  +compiled: CompiledRoute {#461 ▶}
  #router: Router {#26 ▶}
  #container: Application {#2 ▶}
}

【讨论】:

    猜你喜欢
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    相关资源
    最近更新 更多