0

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?

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.