So, I got 2 models called Team
, User
where the User
is related to multiple Teams
and the Team
has multiple Users
included. This means I have a pivot table called team_user
.
I want to grab the team members from a Users.
I have the relations setup as follow:
// In the User model
public function teams()
{
return $this->belongsToMany('App\Entities\Team');
}
// In the Team model
public function users()
{
return $this->belongsToMany('App\Entities\User');
}
How would I return the Users within a Team from a User?
I've tried User::find(1)->teams()->users()
but this isn't working..
I'm trying to return an array like this:
[
'teamName' => 'Team #1',
'users' => [
[
'username' => 'John Doe'
], [
'username' => 'John Doe #2'
]
],
'teamName' => 'Team #2',
'users' => [
[
'username' => 'Doe John'
], [
'username' => 'Doe John #2'
]
]
First, if your pivot table is called team_user
and not team_users
you have to specify it in your relation:
// In the User model
public function teams()
{
return $this->belongsToMany('App\Entities\Team', 'team_user');
}
// In the Team model
public function users()
{
return $this->belongsToMany('App\Entities\User', 'team_user');
}
Then you can retrieve the teams by accessing teams()->get()
of a user and add with('users')
to eager load the users
relationship of every team:
$teams = User::find(1)->teams()->with('users')->get();