In this episode, we tackle a common scenario in multi-team systems: getting a list of all related models (in our case, projects) across all the teams a user belongs to. First, we set up a situation where users are part of multiple teams, each with their own set of projects. For example, Alex belongs to both his own team and Mabel's team, and each team has its own projects. Our goal is to show a combined list of all projects from all these teams in the user's dashboard, regardless of which team is currently active.
At first, it seems like we could use a simple hasManyThrough
relationship on the user model to access all projects, but this doesn't work due to the many-to-many relationship between users and teams (which uses a pivot table). So, we introduce a custom pivot model and use an advanced form of hasManyThrough
, manually specifying all the relevant keys.
After setting this up, we make sure it actually returns all the projects. We then expand the dashboard UI to show a new box listing all these projects and include which team each project belongs to. To avoid performance issues (like the classic N+1 problem), we add eager loading of team data to keep the number of queries down. As a bonus tip, we install Laravel Debugbar to easily inspect our database queries and ensure everything's running efficiently.
By the end of this episode, you'll know how to pull related models across many teams via a pivot table and present them cleanly (and efficiently!) in your app.