如何为Laravel集合使用reduce / reject / map函数?

时间:2016-01-19 12:32:12

标签: php laravel laravel-collection

我目前正使用show中的UserController.php功能来显示属于特定公司的所有用户。

/**
   * 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 个答案:

答案 0 :(得分:0)

你不需要再次收集$ users,试试这个

$names = $users->reject(function ($user) {
return $user->active === false;
})
->map(function ($user) {
return $user->name;
});