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

walter81's avatar

Authorization by pivot table column value

Hi

I've got 3 tables:

Users (id, name)

Clubs (id, name)

club_user (id, club_id, user_id, role). Role can be 'member', 'trainer', 'staff'').

in my User model I have an belongsToMany relation

public function clubs(): BelongsToMany
 {
        return $this->BelongsToMany(Club::class);
 }

Some functionality is reserved to non-members. I'm trying to write an Eloquent query to check if the current user is trainer of staff for at least one of its clubs. I'm trying something like the code below (and some variants) but this return ALL users who have clubs with non-member roles. Not just for the current user. What am I missing here?

Auth::user()->whereHas('clubs')->whereRelation('clubs', 'role', '!=', 'member')->get();
0 likes
1 reply
walter81's avatar
walter81
OP
Best Answer
Level 1

...typical... After struggling for an hour I ask for help only to find it moments later...

Model: 
 public function isClubStaffMember()
    {
        return $this->clubs()->withPivot('role')->where('role', '!=', 'member')->exists();
    }

Check:
Auth::user()->isClubStaffMember(); //returns true or false
´´´´
2 likes

Please or to participate in this conversation.