Have you analysed the underlying query that's being executed?
Something like
dd(Auth::user()->team()->toSql());
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
How do I add a where clause on the pivot table of a belongsToMany relationship?
Using the following relationship, I get an empty collection, even though the relationship is correctly saved into my database.
Without the where clause, I get a collection containing all associated teams. So that works correctly.
public function team()
{
return $this->belongsToMany('App\Team', 'team_user', 'user_id', 'team_id')
->where('team_user.team_id', '=', 'users.current_team_id')
->withPivot([ 'username', 'username_updated_at' ])
->withTimestamps();
}
Auth::user()->team // Returns empty collection
@premsaurav Yes, I already went with that approach. :)
Although I made it look a bit more tidy, with a collection filter:
// Teams relationship (eager loaded)
public function teams()
{
return $this->belongsToMany('App\Team', 'team_user', 'user_id', 'team_id')
->withPivot([ 'joined', 'username', 'username_updated_at' ])
->withTimestamps();
}
// Current Team
public function getTeamAttribute()
{
return $this->teams->where('id', $this->current_team_id)->first();
}
Please or to participate in this conversation.