Chart retunrs first record only... why?

Hi, I'm implementing a chart widget on which I want to display the usage of tags. Models: CommentTag Comment Relationship: Many to many Pivot table: comment_comment_tag The following shows only the first record.
protected function getData(): array
{
$commentTags = CommentTag::with('comments')->get();

$commentTags->loadCount('comments');

foreach ($commentTags as $commentTag) {
return [
'datasets' => [
[
'label' => 'Commnets Tags Usage',
'data' => [$commentTag->comments_count],
],
],
'labels' => [$commentTag->name],
];
}
}
protected function getData(): array
{
$commentTags = CommentTag::with('comments')->get();

$commentTags->loadCount('comments');

foreach ($commentTags as $commentTag) {
return [
'datasets' => [
[
'label' => 'Commnets Tags Usage',
'data' => [$commentTag->comments_count],
],
],
'labels' => [$commentTag->name],
];
}
}
Any advice, thank you.
3 Replies
Patrick Boivin
return needs to happen after foreach, otherwise you exit the loop (and function) on the first pass
LeandroFerreira
$commentTags = CommentTag::withCount('comments')
->pluck('comments_count', 'name')
->toArray();

[$keys, $values] = Arr::divide($commentTags);

return [
'datasets' => [
[
'label' => 'Commnets Tags Usage',
'data' => $values,
],
],
'labels' => $keys,
];
$commentTags = CommentTag::withCount('comments')
->pluck('comments_count', 'name')
->toArray();

[$keys, $values] = Arr::divide($commentTags);

return [
'datasets' => [
[
'label' => 'Commnets Tags Usage',
'data' => $values,
],
],
'labels' => $keys,
];
Pablo Torres
Pablo TorresOP2y ago
Beautiful! Thank you...
Want results from more Discord servers?
Add your server