I'm newbie in Laravel and trying on middleware user role. I created 2 middlewares, 'superadmin' and 'admin' as below.
For superadmin
public function handle($request, Closure $next)
{
if ($request->user() && $request->user()->permission != '1')
{
return new Response(view('unauthorized')->withRole('Super Admin'));
}
return $next($request);
}
For admin
public function handle($request, Closure $next)
{
if ($request->user() && $request->user()->permission != '2')
{
return new Response(view('unauthorized')->withRole('Admin'));
}
return $next($request);
}
I put to my target contoller via __contruct method. There's no problem if controller need only single middleware. But problem on controller that require both middleware (superadmin &admin assessible). I try as below but not work.
public function __construct()
{
$this->middleware('admin');
$this->middleware('superadmin');
}
Appreciated for all advise, thanks.
答案 0 :(得分:0)
您可以创建一个中间件,并具有一个动态参数来验证权限。创建一个新的中间件以确定用户权限。在该中间件中,您可以执行此操作,
public function handle($request, Closure $next, $permission = 0)
{
//allowed only to specified permission
if (($request->user() && $request->user()->permission == $permission) || $permission === 0) {
return $next($request);
}
return new Response(view('unauthorized')->withRole('Admin'));
}
当您应用中间件时,您可以像这样
public function __construct()
{
//allow only admin
$this->middleware('permission:1');
//allow only super admin
$this->middleware('permission:2');
//allow both admin and supper admin
$this->middleware('permission');
}
有关更多信息,请参阅此link。希望这会有所帮助!
答案 1 :(得分:0)
您可以在web.php的路由中使用中间件
Route::group(['middleware' => ['permission1','permission2']], function () {
//
});