Search code examples
laraveleloquentmany-to-manyroles

How to get all Users with a specific Role from a Group model


I have a Group that has a many-to-many relationship with User. And each User can have multiple roles which I implement with spatie/larevel-permission

I am trying to retreive all Users attached to a Group that have a specific role, e.g. learner

this is what i have so far:

class Group extends Model
{
    // other code

    // 
    public function learners(){
        return $this->users::whereHas('roles', function($q) {
            $q->where('name', 'learner');
        })->get();
    }
    
    // other code

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

And I get the error:

Illuminate\Database\Eloquent\Collection::whereHas does not exist

I understand that $this->users returns a Collection, and that's why I get that error message. But I'm not sure how else I could get the users of a group who have the 'learner' role.


Solution

  • You should be calling the relationship method users() which returns the Belongs To Many relationship not the dynamic property users which returns the result of the query for the relationship (Collection). Also you could make the learners method a relationship method itself instead of directly returning the result:

    public function learners()
    {
        return $this->users()
            ->whereHas('roles', fn ($q) => $q->where('name', 'learner'));
    }
    
    $group->learners;
    

    It all depends what you intend to do with this method.