I'm having a small conditional loop in my application built on Laravel 5.5
, I'm learning collections
which seems to be amazing when I know more, currently I'm having following code in my controller:
$milestone = Milestone::where('unique_id', $id)
->with('project.teams.users.profile')
->first();
// $users = $milestone->project->pluck('teams.users');
$users = [];
foreach ($milestone->project->teams as $team)
{
foreach($team->users as $user)
$users[] = $user;
}
return response()->json(['users' => $users], 200);
In my code i tried $users = $milestone->project->pluck('teams.users');
is not giving me proper result, In my model milestone following is relationship:
public function project()
{
return $this->belongsTo('App\Models\Team\Project', 'project_id');
}
In my Project relationship is:
public function teams()
{
return $this->belongsToMany('App\Models\Team\Team', 'project_team', 'project_id', 'team_id');
}
In my Teams model:
public function users()
{
return $this->belongsToMany('App\Models\User')->withTimestamps();
}
This might by two many to many relationship between project->teams
and teams->user
I'm not getting the result.
I want to omit this foreach
loop through collection
, Can someone guide me how to implement this through the same, Thanks
Laravel collections have awesome flatten()
method.
It flattens a multi-dimensional collection into a single dimension.
So you can use pluck()
and then flatten()
to get users from all teams as one collection and omit foreach
loop:
$users = $milestone->project->teams->pluck('users')->flatten();
It is will return all users from a single project as collection, so you will be able to loop users via each()
method:
$users->each(function($user){
//your code here
});