Relationship with three columns to get Roles and Permissions
Hello, i have a team, project, user, role, permissions relationship in laravel.
User can have many teams, a team can have many projects and user can have User role, team role and project role. How can i get the user permissions for every project, every team and for user only? Let me show you the tables to explain better.
User table
- Id
- name
- current_project_id
- current_team_id
- role_id
- etc
Teams table
- id
- name
Projects table
- id
- name
- description
Roles table
- id
- name
- type(user,project,team) Permissions table
- id
- name
Role_permission table
- permission_id
- role_id
project_user table
- project_id
- user_id
- role_id
team_user table
- team_id
- user_id
- role_id
The user only can have 1 role for 1 project, 1 role for 1 team and 1 role for user, it should be admin or user.
I'm trying to get the user project roles like that, also i've skipped the teams code, because i think that is very similar to projects code.
class User extends Authenticatable
{
public function projectRole()
{
//I can't find the way to insert project_id like in where, because current_project_id is null in boot
return $this->belongsToMany(Role::class, 'project_user')->where('project_id', '=', $this->current_project_id)->first();
}
public function projectPermissions()
{
return $this->projectRole()->permissions;
}
public function permissions()
{
//I can't find the way to get all team permission, project permissions and user permissions
}
public function role() : BelongsTo
{
//Only can be User role, Admin or Support
return $this->belongsTo(Role::class);
}
public function userPermissions()
{
return $this->role->permissions;
}
}
class Role extends Model
{
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
}
I want to use permissions as a gate, to pass to inertia front end, i'm trying something like that
Gate::before(function ($user, $permission) {
return $user->projectPermissions($user->currentProject)->contains($permission) || $user->teamPermissions($user->currentTeam)->contains($permission) || $user->teamPermissions($user->currentTeam)->contains($permission)
|| $user->userPermissions()->contains($permission);
});
Please or to participate in this conversation.