如何获取动态路由前缀

how to get dynamic route prefix

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

我在我的 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));
}

但给我错误 函数参数太少...

有一些数据不可用于中间件,因为它在生命周期的早期就启动了。会话数据不可用,并且似乎在中间件 运行 之前路由尚未完全形成。不过,您可以使用另一种方法 return 将参数传递给路由。

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

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

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

应该能满足您的需求。

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

\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 ▶}
}