我有一个角色中间件,可以将参数传递给中间件。
public function __construct(UserInterface $user, RoleInterface $role, MaritalStatusInterface $maritalStatus, CityInterface $city){
$this->middleware('auth');
//$this->middleware('role:System Admin'); I changed it to 6 for the id.
$this->middleware('role:6');
}
My RoleMiddleware就是这个
public function handle($request, Closure $next, ...$params)
{
$roles = $request->user()->roles()->get();
$roles = $roles->map(function($item){
return $item->id;
});
foreach ($params as $value) {
if( ! in_array($value, $roles->toArray())){
return redirect()->action('NavController@home');
}
}
return $next($request);
}
正如您所看到的,它与6
密切相关。如果我想添加7
怎么办...我想动态制作它。我的表格为Users
Role_User
和Roles
。我需要什么表以及如何执行它。
答案 0 :(得分:1)
因为你想要它是动态的,你应该有一个允许角色的数据库..然后你应该在同一个控制器中
$allowedRoles = AllowedRoles::all();
$loop=1;
foreach($allowedRoles as $role)
{
$roleString = $loop == 1 ? $role->value : $roleString.'|'.$role->value;
// where value is equivalent to the role of your role id in role database
$loop++;
}
$this->middleware('role:'.$roleString);
然后在你的中间件中你应该爆炸roleString
public function handle($request, Closure $next, $roles)
{
$roles = explode('|',$roles);
$user = User::find($request->user()->id);
foreach($user->intRoles as $myRole)
{
if(in_array($myRole->role_id, $roles))
{
return $next($request);
}
}
// Redirect
return redirect()->back();
}