Just guessing, but do you want to group for presentation purpose? Or for calculation/statistics purpose?
Does the pivot_parent columns references to the primary id in the quiz table or is it some other value?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm trying to group related model by pivot data, but this returns only one record of the related for each group. How can I group quiz records by column parent, which is saved in pivot table?
$user = User::where('id', $id)
->with(['quiz' => function($query) use ($md) {
$query->where('md_id',$md)->groupBy('pivot_parent');
}])
->first();
groupBy on the relation eager loading will apply the GROUP BY clause on the SQL query executed to fetch the quiz records.
Try grouping after fetching
$user = User::query()
->where('id', $id)
->with([
'quiz' => function ($query) use ($md) {
$query
->withPivot('pivot_parent')
->where('md_id', $md);
},
])
->first();
$grouped = $user->quiz->groupBy('pivot_parent');
This will group the query results. You will end up with two variables, but if you want only one you can dynamically add to the user instance like this:
$user->grouped = $user->quiz->groupBy('pivot_parent');
Please or to participate in this conversation.