Laravel 5 - 在资源中间件中获取 URL 参数

Dak*_*ter 4 php laravel

假设我在我的路由中定义了一个资源:

Route::resource('account', 'AccountController', ['only'=> ['index','update']]);
Run Code Online (Sandbox Code Playgroud)

然后我从内部Middleware附加到Controller

public function __construct() {
    $this->middleware('BeforeAccount', ['only' => ['update']]);
}
Run Code Online (Sandbox Code Playgroud)

假设我想访问example.com/account/2在我的中间件中的帐户(即)之后发生的 uri 参数- 我该如何获取该变量?

The*_*pha 6

您可以使用以下代码来实现:

public function handle($request, Closure $next)
{
    $account_id = $request->route()->parameter('accounts');

    //...
}
Run Code Online (Sandbox Code Playgroud)

由于该handle方法接收Request对象作为第一个参数。在middleware只有在路线已被匹配,因此被执行Request对象包含当前的路由,无需再次使用匹配的路由Route::getRoutes()->match($request)