角色中间件动态参数Laravel 5.4

时间:2017-05-18 04:50:20

标签: laravel

我有一个角色中间件,可以将参数传递给中间件。

 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_UserRoles。我需要什么表以及如何执行它。

1 个答案:

答案 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();
}