Dan E
Dan E

Reputation: 177

Building an array in nested foreach loops in Laravel controller

I am trying to build an array of user ids from a long eloquent relationship, using nested foreach loops in a Laravel controller, but can't get it to work.

Users can have publishers, those publishers can have teams and each team has members. Users can be in multiple teams so I also need to remove duplicate IDs.

I want to end up with a count to see how many team members are associated with a user.

In my user model

public function publishers()
{
    return $this->belongsToMany('App\Publisher')->withTimestamps();
}

In my publisher model

public function teams()
{
  return $this->belongsToMany('App\Team')->withTimestamps();
}

and in my team model

public function members()
{
  return $this->belongsToMany('App\User')->withPivot('status', 'title', 'team_role_ids')->withTimestamps();
}

and in my profile controller

foreach ($user->publishers as $userPublisher) {
  foreach ($userPublisher->teams as $publisherTeam) {
    $teamUserIds[] = $publisherTeam->members->pluck('id')->toarray();
  }
}
$deDupedIds = array_unique($teamUserIds, SORT_NUMERIC);
$idsCount = count($deDupedIds);

But I'm getting multiple arrays and not just one compiled array and the count isn't working. Any idea what I'm doing wrong?

Upvotes: 0

Views: 2311

Answers (2)

bdtiger
bdtiger

Reputation: 521

You are assigning a new array into $teamUserIds each iteration. That's why you are getting multiple arrays.

$teamUserIds = [];
foreach ($user->publishers as $userPublisher) {
  foreach ($userPublisher->teams as $publisherTeam) {
    $teamUserIds = array_merge($teamUserIds, $publisherTeam->members->pluck('id')->toarray());
  }
}
$deDupedIds = array_unique($teamUserIds, SORT_NUMERIC);
$idsCount = count($deDupedIds);

Upvotes: 1

Hamidreza
Hamidreza

Reputation: 724

you are adding arrays of id $publisherTeam->members->pluck('id')->toarray(); as a new index in $teamUserIds . but what you want to do is to merge the array of ids

so your code would be like this :

foreach ($user->publishers as $userPublisher) {
  foreach ($userPublisher->teams as $publisherTeam) {
    $teamUserIds = array_merge($teamUserIds , $publisherTeam->members->pluck('id')->toarray());
  }
}
$deDupedIds = array_unique($teamUserIds, SORT_NUMERIC);
$idsCount = count($deDupedIds);

Upvotes: 0

Related Questions