1
votes

User.php

public function roles(){ return $this->belongsToMany(Role::class); }

Role.php

public function users(){ return $this->belongsToMany(User::class); }

UserController.php

$user = User::whereHas('roles', function ($q) use ($request) { $q->where('role_id', $request->roles); })

================Request========================

{ "roles":[1,2] }

===============Response=========================

[]

===============Table=============================== role_user

+===+===+
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
| 3 | 2 |
| 4 | 2 |

What should i do to get all the users with exactly two roles? as user 1 has 2 roles in database

3
use whereIn in your controller query.Akhtar Munir

3 Answers

0
votes

You can use whereIn to only get users with the provided role_ids:

Role 1 or 2:

$user = User::whereHas('roles', function ($q) use ($request) {
    $q->whereIn('role_id', $request->roles); // $request->roles needs to be an array
});

Role 1 and 2:

$user = User::whereHas('roles', function ($q) use ($request) {
    $q->whereIn('role_id', $request->roles)
        ->groupBy('user_id')
        ->havingRaw('COUNT(DISTINCT role_id) = '.count($request->roles));
});

From the docs:

The whereIn method verifies that a given column's value is contained within the given array

$users = DB::table('users')
    ->whereIn('id', [1, 2, 3])
    ->get();
0
votes

You can count the amount of roles in your query and then use the result as an attribute

$users = User::withCount('roles')->get()->where('roles_count',2);
0
votes

You can try this

Public function getRole()
$users=User::with('roles') - >first () ;
foreach ($users->roles as $user)
 {
$list[] =$user->name;
}
dd($list) ;