I'm currently using the show
function in my UserController.php
to show all the users belonging to a particular company.
/**
* Show the list of all users.
*
* @return Response
*/
public function show() {
$users = User::where('status',1)->with(['phones', 'companies'])->get(['id', 'first_name', 'last_name', 'email']);
$filteredUsers = [];
foreach($users as $user){
foreach($user->companies as $company){
if($company->id == session('selected_company')){
$filteredUsers[] = $user;
}
}
}
return view('users', ['team_members' => $filteredUsers]);
}
This works perfectly fine, but I want to make the code more elegant with Laravel collections, hopefully with a map()
, reject()
or reduce()
function
How can I do so?
I tried the reject()
function but it keeps showing me all the users in the database. Here's what I tried:
/**
* Show the list of all users.
*
* @return Response
*/
public function show() {
$users = User::where('status',1)->with(['phones','companies'])->get(['id', 'first_name', 'last_name', 'email']);
$userCollection = collect($users);
$filteredUsers = $userCollection->reject(function ($value) {
$userCompanies = collect($value->companies);
// if user companies contain the id, return that user
if($userCompanies->contains('id', session('selected_company'))){
return $value;
}
});
return view('users', ['team_members' => $filteredUsers->all()]);
}