Laravel use resource controller method $id parameter as middleware parameter

泪湿孤枕 提交于 2019-12-25 04:20:01

问题


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.

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)
{
  //
}

回答1:


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
}

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



来源:https://stackoverflow.com/questions/39118423/laravel-use-resource-controller-method-id-parameter-as-middleware-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!