首页 文章

Laravel用户管理

提问于
浏览
0

在Laravel中,我们可以轻松管理用户和权限,但我的应用程序出了问题 .

在我的应用程序中,用户被附加到一个或多个部门 .

但是用户可以在部门之间具有不同的角色/权限 . 那就是问题所在 . 在部门One中,他可以拥有管理员角色,在部门2中,他只能拥有用户角色 . 当用户在部门之间切换时,我希望他的角色可以更新 .

我如何在Laravel和Eloquent中管理这个?

谢谢您的帮助 .

杰弗里

1 回答

  • 3

    没有看到你的任何代码,我被迫在这里相当通用 . 但这是基本概念 .

    架构

    假设您已经拥有 departmentsusersrolespermissions 这样的表,那么您接下来需要的就是定义一个连接表 . 像这样的东西:

    • department_role_user

    • department_id //这个部门

    • role_id //此角色已分配给

    • user_id //这个用户

    授权

    在User模型上定义类似 hasPermissionTo() 方法的内容 .

    定义

    class User
    {
        public function hasPermissionTo($action, $department)
        {
            // first get permission
            $permission = Permission::where('action', $action)->first();
    
            // get all roles which have this permission
            $roles = $permission->roles;
    
            return DB::table('department_role_user')
                ->where('user_id', $this->id) // current user
                ->where('department_id', $department->id) // the dept
                ->whereIn('role_id', $roles->pluck('id')) // any of the roles
                ->exists();
        }
    }
    

    用法

    并像这样使用它 .

    if ($user->hasPermissionTo('do-something', $someDept)) {
        // allow action
    } else {
        // no way
    }
    

    这也应该与Laravel的GatesPolicies很好地配合 . 只需在门/策略定义中使用新的 hasPermissionTo() 方法 .

相关问题