DolDurma
DolDurma

Reputation: 17289

Laravel get only users which they have specific Role using RelationShip

In my Laravel implemented web application i have Users and Roles tables with models which they are ManyToMany.

i want to get all users which they have specific role, for example:

$users = User::with(['roles' => function ($query) {
    $query->whereLabel('is-portal-manager');
}])->get();

unfortunately this code return all users and compare role label and return that in relation ship array

Illuminate\Database\Eloquent\Collection {#2069 ▼
  #items: array:3 [▼
    0 => App\User {#2076 ▼
      ...
      #relations: array:4 [▼
        "properties" => null
        "child" => Illuminate\Database\Eloquent\Collection {#2073 ▶}
        "parent" => null
        "roles" => Illuminate\Database\Eloquent\Collection {#2087 ▼
          #items: array:1 [▼
            0 => App\Entities\Role {#2074 ▼
              ...
              #attributes: array:5 [▼
                "id" => 1
                ...
                "label" => "is-portal-manager"
                ...
              ]
              ...
            }
          ]
        }
      ]
      ...
    }
    1 => App\User {#2077 ▼
      ...
      #relations: array:4 [▼
        "roles" => Illuminate\Database\Eloquent\Collection {#2093 ▼
          #items: []
        }
      ]
      ...
    }
  ]
}

as you can see in above output second user doesn't have any role and #items: [] is empty. i don't need to have this output structure and i want to have only which users have specific role, not all users with empty roles. second item of this collection shouldn't this output

Upvotes: 1

Views: 656

Answers (1)

Metabolic
Metabolic

Reputation: 2904

Make your relationship conditional by using Laravel's whereHas:

$users = User::whereHas('roles', function ($query) {
    $query->whereLabel('is-portal-manager');
})->with('roles')->get();

Official documentations for further reading on Eloquent Relationship Existence methods whereHas, has, doesntHave and whereDoesntHave

Upvotes: 2

Related Questions