When we use groupBy in api resources its class doesnt accept the key and we cannot modify the json:
public function toArray($request)
{
return [
'comments' => CommentResource::collection($this->comments->groupBy('someColumn')),
];
}
Property [someColumn] does not exist on this collection
Without using CommentResource it will work:
public function toArray($request)
{
return [
'comments' => $this->comments->groupBy('someColumn'),
];
}
But we cannot modify the comments columns in its json response and it returns all columns.
When you call groupBy on the comments collection, you're not getting back a collection of models. You're getting back a collection of keys that contain a collection of models.
You could possibly group the collection once it has been created.
CommentResource::collection($this->comments)->collection->groupBy('someColumn')
Most helpful comment
When you call groupBy on the comments collection, you're not getting back a collection of models. You're getting back a collection of keys that contain a collection of models.
You could possibly group the collection once it has been created.
CommentResource::collection($this->comments)->collection->groupBy('someColumn')