Laravel使用资源控制器方法$ id参数作为中间件参数 [英] Laravel use resource controller method $id parameter as middleware parameter

查看:117
本文介绍了Laravel使用资源控制器方法$ id参数作为中间件参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个中间件来检查用户是否具有查看某些页面所需的权限.下面是我当前用来调用中间件的代码.现在,我传递用户需要具有的角色的名称,但我也想传递调用store方法时使用的必需ID.

I am trying to make a middleware to check if the user has the permissions required to view certain pages. Below the code that I currently use to call the middleware. I now pass the name of the role the user needs to have but I also want to pass through the required id that is used when the store method is called.

是否有办法做到这一点,还是应该在该控制器中单独执行一个功能,还是应该将路由检查中间件移至routes.php?我不想移动它,因为这意味着我必须重新定义资源控制器已经定义的所有路由.

Is there a way to do this or should I make either a seperate function in this controller or move the route checking middleware to the routes.php? I prefer not to move it because this would mean I have to redifine all the routes that are already defined by my resource controller.

public function __construct()
{
    $this->middleware('permission:Manager',['only' => [
        'show',
    ]]);
}

public function show($id)
{
  //
}

推荐答案

您可以在中间件的handle方法中访问$request对象,以获取所请求页面的ID和执行请求的用户,例如:

You can access $request object in the handle method of your middleware to obtain id of the requested page and the user performing the request, e.g.:

public function handle($request, Closure $next, $role)
{
    if ( $request->user() && $request->has('id'))
    {
        if ($request->user()->hasRole($request->id, $role)
            return $next($request);
    }        
    return redirect('/403');  // redirect when not allowed
}

请注意,hasRole方法和$role参数只是您自己的方法和参数的占位符名称.

Please note the hasRole method and the $role parameter are just placeholder names for your own method and parameter.

这篇关于Laravel使用资源控制器方法$ id参数作为中间件参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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