3

I have to get specific data like "roles" table have filed status and i need status = 1 that all data get from the role table

$result = User::select()
    ->with('roles')
    ->where('email', $email)
    ->get();
    return $result;

2 Answers2

3

Following the answers to this question: Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean? If I understood correctly how your data model is structured:

  • User has many Roles
  • Role has a property status
  • Want to filter by status = 1
$users = User::whereHas('roles', function($q){
    $q->where('status', '1');
})
->where('email', $email)
->get();

EDIT: I am not happy with the answer above because in that case as far as I understood, the Users returned do not have the list of roles already loaded, so I checked the documentation (https://laravel.com/docs/5.8/eloquent-relationships) and given what I found, the following code should do what you ask:

$users = User::with(['roles' => function ($query) {
    $query->where('status', '1');
}])
->where('email', $email)
->get();

I never used eloquent nor laravel and I am not a php developer, so I could not try this snippet, please if it is not correct let me know.

Norcino
  • 5,850
  • 6
  • 25
  • 42
  • 1
    As a Laravel developer; You are correct. This code will fetch the users with their roles (eager loading) but just the users where the query for the roles returns true. – Douwe de Haan Apr 12 '19 at 07:52
2

You can write subQuery like

$result = User::select()
    ->with(['roles' => function($q){    
         $q->where('status', 1);
    }])
    ->where('email', $email)
    ->get();
    return $result;
Nikunj K.
  • 8,779
  • 4
  • 43
  • 53