2

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()]);
  }
maxxon15
  • 1,559
  • 4
  • 22
  • 35
  • You can make your code more elegant if you filter users by company in eloquent / sql, rather than fetching all users from database and rejecting/reducing it in php. – Alex Blex Jan 19 '16 at 12:43
  • @AlexBlex I figured that, but the companies data is in a separate table. How can I filter that using eloquent? – maxxon15 Jan 20 '16 at 07:09
  • 1
    Yes, of course it is.There are several ways to achieve that: https://laravel.com/docs/5.0/eloquent#querying-relations, https://laravel.com/docs/5.0/queries#joins, or even raw sql. Please try and ask another question if you have any problems with fetching such data. – Alex Blex Jan 20 '16 at 09:36
  • @AlexBlex Ah I see. Thanks for that. Unfortunately Laravel 5.2 documentation doesn't say anything about `has` or `whereHas`. – maxxon15 Jan 20 '16 at 10:27

1 Answers1

0

you don't need to make collect again $users,try like this

$names = $users->reject(function ($user) {
                    return $user->active === false;
                 })->map(function ($user) {
                    return $user->name;
                 });
NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22
Imtiaz Pabel
  • 5,307
  • 1
  • 19
  • 24
  • This would certainly get rid of the `('status',1)` portion, but I was kinda hoping to do the same thing instead of the 2 `foreach` loops there. :) Any clue? – maxxon15 Jan 20 '16 at 07:15