Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FireBlade's avatar

Policy within many-to-many relationships

I have this table structure:

Users
	id - integer
    name - string
Roles
	id - integer
    name - string
Groups
	id - integer
    name - string
GroupRoles
	group_id - integer
    role_id - integer
GroupUsers
	user_id - integer
	group_id - integer
Posts
	id - integer
	user_id - integer
    description - string

I already have the relationships established on the models i.e.

Role

public function groups()
	{
		return $this->belongsToMany(Group::class);
	}
}

User

public function group()
	{
		return $this->belongsToMany(Group::class);
	}
}

Group

public function user()
	{
		return $this->belongsToMany(User::class);
	}

    public function role()
	{
		return $this->belongsToMany(Role::class);
	}
}

How do I authorize a user on the PostPolicy viewAll policy method with a Role called POST_VIEW?

0 likes
3 replies
FireBlade's avatar
FireBlade
OP
Best Answer
Level 2

SOLVED Typehint the GroupRight model on the PostPolicy and initialize it on the policy constructor then

public function viewAny(User $user)
    {
        return Groupright::join('roles','roles.id','=','group_rights.role_id')
        ->where('description', 'POST_VIEW')
        ->where('group_rights.group_id','=', $user->group()->first()->id)
        ->exists();
    }
1 like

Please or to participate in this conversation.