Sebastian Olsen
Sebastian Olsen

Reputation: 10888

How to query a relationship through a relationship collection

I have a user and a department, a user can belong to many departments. I'm trying to define a scope on the user model to only show users of departments that the current user is a part of:

public function scopeVisible($query) {
    $user = Auth::user();

    return $user->departments()->users();
}

I've looked at the documentation and can't seem to find a way to do this.

I tried mapping but got strange errors where a method call would be on a query builder instead of a collection even though the object is a collection.

Upvotes: 1

Views: 59

Answers (1)

Troyer
Troyer

Reputation: 7013

As Laravel docs says you can use whereHas to add customized constraints for more specific queries:

If you need even more power, you may use the whereHas and orWhereHas methods to put "where" conditions on your has queries. These methods allow you to add customized constraints to a relationship constraint.

Then this should work:

public function scopeVisible($query) {
    $user_id = Auth::user()->id;

    return $query->whereHas('departaments', function($query) use ($user_id) {
      $query->where('user_id', '=', $user_id);
    });
}

The error you are getting about "the method call must be on a query builder instead of a collection" it's because on your code you are returning the result of $user->departments()->users(), which is a collection of Departments, you should return the query builder instead.

Upvotes: 1

Related Questions