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

时间:2015-07-29 22:24:25

标签: php laravel

假设我的路由中定义的资源为:

Route::resource('account', 'AccountController', ['only'=> ['index','update']]);

然后我将Middleware附加到内部的Controller作为:

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

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

2 个答案:

答案 0 :(得分:2)

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

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

    //...
}

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

答案 1 :(得分:0)

这样做你不必提供\ Request对象:

error C2039: 'System' : is not a member of 'Windows'
error C2871: 'System' : a namespace with this name does not exist
error C2039: 'Storage' : is not a member of 'Windows'
error C2871: 'Storage' : a namespace with this name does not exist
error C2039: 'ApplicationModel' : is not a member of 'Windows'
error C2871: 'ApplicationModel' : a namespace with this name does not exist
error C3083: 'ApplicationModel': the symbol to the left of a '::' must be a type