2

I am trying to fetch users based on their role_id from database through ajax. I did this using below code.

        $queryModel->whereHas('roles',function ($query) use ($role_id) {
           $query->where("role_id",$role_id);
        });

But on live server I have more than 40,000 users so it takes a lot of time to fetch data. This is because of using whereHas().I tried using where but it did not work. is there any solution which makes search fast.

Saad Ramay
  • 152
  • 1
  • 11

1 Answers1

0

If you have a Role model which also have a relation with User model you can try something like this;

$role = Role::findOrFail($role_id);
$users = $role->users; // got all users which have that specific role
// or you can use query builder
$users = $role->users()->where('name', 'like', 'U%')->get();

As a result you don't need to check all users to find which of them have a specific role. You start with role and access it's users.

Uğur Arıcı
  • 1,180
  • 1
  • 10
  • 16
  • it is not working the way it should. It gets all the user of that role but I want only the ones searched by user. for example if I search for "Cut" it should give me the one(s) whose name start with "cut" like cutting company etc – Saad Ramay Aug 04 '21 at 14:36
  • If you use `$role->users()->where('name', 'like', 'U%')->get();` it creates a query builder with `$role->users()` and add where clause on it, it runs the result query. So it doesn't fetch all users on that role. But if you directly use `$role->users` it fetches them all. You need to use it with parentheses. – Uğur Arıcı Aug 04 '21 at 14:43