LSteamGeo
LSteamGeo

Reputation: 3

Laravel user management

In Laravel we can manage Users and Permissions easly but i've a problem with my application.

In my application a User is attached to One or Many department.

But a User can have different Role/Permission between departments. That is the problem. In the department One he can have a Admin Role and in the department Two he can only have a User Role. When the User switch between department i would like that his Role can be update.

How i can manage this in Laravel and Eloquent ?

Thank you for your help.

Jeffrey

Upvotes: 0

Views: 536

Answers (1)

John
John

Reputation: 3916

Without seeing any of your code, I am forced to be fairly generic here. But here is the basic concept.

Architecture

Assuming you have tables like departments, users, roles, and permissions already, all you would need next is define a joining table. Something like this:

  • department_role_user
    • department_id // for this department
    • role_id // this role is assigned to
    • user_id // this user

Authorization

Define something like a hasPermissionTo() method on your User model.

Definition

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

Usage

And use it like so.

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

This should also work nicely with Laravel's Gates and Policies. Just use your new hasPermissionTo() method inside your gate/policy definitions.

Upvotes: 3

Related Questions