Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

User1980's avatar

Unable to only select users based on certain role

Hello,

I am using spattie and would like to only show users with the role "user".

But when I use this query:

$users = User::whereHas(
            'roles', function ($query) {
            $query->where('name', 'user');
        })
            ->with([
                'chats' => function ($query) {
                    $query->orderBy('id', 'DESC');
                }])
            ->paginate(25);

It still shows also the admins.

Any idea why please?

Thank you.

0 likes
10 replies
User1980's avatar

@Nakov I tried your solution(thank you).

When doing this on the first request it works:

$users = User::role('user')

But as soon as I do this(search bar).

        $users = User::role('user')
            ->when($search, function ($query) use ($search) {
                $query->where('email', 'LIKE', "%{$search}%");
            })
            ->paginate(25);

I am getting all the admins with the results. It looks like the when() close is causing problems.

Sinnbeck's avatar

@User1980 why do you have a group by? Seems out of place. Does it work without it?

Otherwise check the actual query made using debugbar or clockwork

User1980's avatar
User1980
OP
Best Answer
Level 4

@Sinnbeck The problem got resolved when I added: ->role('user')

At the end of the query (before the paginate).

Snapey's avatar

Whats the point of groupBy on a list of unique ids

Please or to participate in this conversation.