Laravel 5-在资源上的中间件中获取URL参数 [英] Laravel 5 - Getting URL Parameters in Middleware on Resources

查看:172
本文介绍了Laravel 5-在资源上的中间件中获取URL参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在路线"中定义了以下资源:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆