问题
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