In this episode, we kick off a new mini-series all about working with related models through teams in our Laravel app. We're starting simple: the goal here is to list projects on our dashboard that belong to the team we're currently viewing. When you switch teams, you should see a totally different set of projects. While we're focusing on projects as our example, you could easily adapt everything here to other related models too.
We start by setting up a new Project
model (plus migration and factory), making sure projects belong to a team via a foreign key. We also keep things clean and simple in the migration—just a title and the team_id
for now. Once that's set, we use the factory to bang out a few fake projects in the database for our demo team.
Then, we move over to structuring our controller properly by introducing a new DashboardController
. In it, we fetch all projects for the current team and pass them down to the dashboard view. On the frontend, we loop over each project and display its title.
We double-check that project visibility is working as intended by logging in as another user (with a different team) and confirming they see only their team's projects—so the scoping is working!
To keep things tidy, we wrap up by mentioning that, in the next episode, we’ll create a convenient helper to avoid repeating ourselves every time we need to grab a team's projects. We'll also get into some tests to make sure everything is solid.