Search code examples
collectionseloquentunique

eloquent collection - unique field on relationship


I have a User model and a Team model, and there can be many users (belongsToMany relatioship) in a Team. What I need now is to extract a list of all users from the teams that the logged in user is a member of.

I have below code currently:

$teams = $user->teams()->get()->pluck('id')->toArray();

    return Team::whereIn('id', $teams)->with(['users'])->get()->map(function ($item) {
        return $item->users->map(function ($user) {
            return [
                'name' => $user->name,
                'email' => $user->email,
            ];
        });
    });

Above returns a collection, similar to below:

Collection {#375 ▼
  #items: array:2 [▼
    0 => array:3 [▼
      0 => array:2 [▼
        "name" => "John Doe",
        "email" => "[email protected]"
      ]
      1 => array:2 [▼
        "name" => "Jane Doe",
        "email" => "[email protected]"
      ]
      2 => array:2 [▶]
    ]
    1 => array:2 [▼
      0 => array:2 [▼
        "name" => "Jane Doe"
        "email" => "[email protected]"
      ]
      1 => array:2 [▼
        "name" => "John Doe",
        "email" => "[email protected]"
      ]
    ]
  ]
}

Here's a better view:

[
  [
    {
      "name": "John Doe",
      "email": "[email protected]"
    },
    {
      "name": "Jane Doe",
      "email": "[email protected]"
    },
    {
      "name": "John Doe",
      "email": "[email protected]"
    }
  ],
  [
    {
      "name": "Jane Doe",
      "email": "[email protected]"
    },
    {
      "name": "John Doe",
      "email": "[email protected]"
    }
  ]
]

As you can see I have duplicates, I need to get rid of those. I've tried using distinct and unique without success.


Solution

  • I partly solved it by using a foreach loop, but would prefer if I could get this data using the eloquent query.

    $userArray = array();
        foreach ($users as $user) {
            if (array($user)) {
                foreach ($user as $u) {
                    $userArray[] = $u['email'];
                }
            } else {
                $userArray[] = $user['email'];
            }
        }
        return array_unique($userArray);