you are using pluck wrong I think. Use get() instead or reverse the parameters
the second parameter is the key
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hey everyone!
I have this query
$reviewArr = Review::select('stars', \DB::raw('COUNT(*) as total'))
->where('website_id', $request->website_id)
->groupBy('stars')
->pluck('stars', 'total');
which is supposed to print an array like
#items: array:1 [▼
1 => 15,
2 => 31,
3 => 81,
4 => 64,
5 => 75
]
which is actually an count on how many reviews for each rating possible (1-5) a specific website have. As you can see 1star count = 15, 2star count = 31, 3star count = 81 etc... But it is not working properly. Sometimes it's showing strange result like
#items: array:1 [▼
1 => 5
]
Which is not correct. The result printed is for website id 2, and I can clearly see that website id 2 has 5 reviews (one 1star, one 2star, one 3star, one 4star and one 5star) so this means the query is not working properly. What might be the problem? Here's my full code
$reviewArr = Review::select('stars', \DB::raw('COUNT(*) as total'))
->where('website_id', $request->website_id)
->groupBy('stars')
->pluck('stars', 'total');
dd($reviewArr);
$totalReviews = Review::where('website_id', $request->website_id)->count();
return response()->json([
'html' => view('admin.ajaxViews.addbulkDonutchart', [
'website' => Website::find($request->website_id),
'total' => $totalReviews,
'onestar' => $reviewArr[1] ?? 0,
'twostar' => $reviewArr[2] ?? 0,
'threestar' => $reviewArr[3] ?? 0,
'fourstar' => $reviewArr[4] ?? 0,
'fivestar' => $reviewArr[5] ?? 0,
])->render(),
'total' => $totalReviews,
'onestar' => $reviewArr[1] ?? 0,
'twostar' => $reviewArr[2] ?? 0,
'threestar' => $reviewArr[3] ?? 0,
'fourstar' => $reviewArr[4] ?? 0,
'fivestar' => $reviewArr[5] ?? 0,
]);
@Laralex No,no no
DB::table('reviews')
->select(DB::raw('stars, count(*) as count'))
->where('website_id',5)
->groupBy('stars')
->get()
->pluck('count','stars');
Please or to participate in this conversation.