Laravel 5-在资源上的中间件中获取URL参数 [英] Laravel 5 - Getting URL Parameters in Middleware on Resources
问题描述
假设我在路线"中定义了以下资源:
Let's say that I have a resource defined in my Routes as:
Route::resource('account', 'AccountController', ['only'=> ['index','update']]);
然后,我将Middleware
从内部附加到Controller
上:
And then I have the Middleware
attached to the Controller
from within as:
public function __construct() {
$this->middleware('BeforeAccount', ['only' => ['update']]);
}
假设我要访问在中间件中帐户(即example.com/account/2
)之后发生的uri参数-我该如何获取该变量?
Let's say I want to access the uri parameter that happens after account (i.e. example.com/account/2
) within my Middleware - how do I go about grabbing that variable?
推荐答案
您可以使用以下代码来实现:
You can use the following code to achieve that:
public function handle($request, Closure $next)
{
$account_id = $request->route()->parameter('accounts');
//...
}
由于handle
方法接收到Request
对象作为第一个参数. middleware
仅在路由已匹配之后才执行,因此Request
对象包含当前路由,无需使用Route::getRoutes()->match($request)
再次匹配该路由.
Since the handle
method receives the Request
object as the first argument. The middleware
gets executed only after the route has been matched so the Request
object contains the current route and no need to match the route again using Route::getRoutes()->match($request)
.
这篇关于Laravel 5-在资源上的中间件中获取URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!