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

david001's avatar

How to Query GroupBy

I have users,quizzes and quiz_users table.

users table have id/name/email/password/timestamps

quizzes table have id/name/description/timestamps

quiz_users table have id/user_id/quiz_id

so i have 2 model

User.php and Quiz.php and quiz_users is pivot table, it contains the particular quiz assigned to particular user, user_id and quiz_id

Now i want to fetch all users groupBy quiz_id, how can i query it? i tried in this way

User::has('quizees')->groupBy('user_id')->paginate(10); 

but it has error. Any help is highly appreciated.

0 likes
3 replies
ERashdan's avatar

What's the goal of this query ? To list all users only with quiz id ?

david001's avatar

to list users along with quiz name for exam john may be assigned to quiz example , quiz1, and quiz2

so output should be

name quiz

John quiz1,quiz2

ERashdan's avatar
ERashdan
Best Answer
Level 15

Why not try this in controller

$users = User::whereHas('Quizzes')->paginate();

In blade

@foreach($users as $user) 
    {{ $user->name }}
    @foreach($user->Quizzes as $quiz)
        {{ $quiz->name }}
    @endforeach
@endforeach

Please or to participate in this conversation.