我目前正在使用UserController.php
中的show
函数来显示属于某个特定公司的所有用户。
/**
* 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]);
}
这非常好用,但是我希望使用Laravel集合使代码更优雅,希望使用map()
、reject()
或reduce()
函数
我怎么能这样做呢?
我尝试了reject()
函数,但它总是显示数据库中的所有用户。
/**
* 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()]);
}
1条答案
按热度按时间bvjxkvbb1#
你不需要使收集再次$users,尝试象这样