Mwthreex
Mwthreex

Reputation: 1059

Using groupBy in Laravel resource

I want to pass a collection with a groupBy in laravel resource, But the problem is when i use that with collection method I can not modify the json and it throws a error:

PostResource:

public function toArray($request)
{
    return [
        'comments' => CommentResource::collection($this->comments->groupBy('star')),
    ];
}

Property [star] does not exist on this collection

But as soon as I remove the groupBy method from the collection it works. So how to get and modify the resource when it is grouped by with a specific key ?

Upvotes: 3

Views: 4549

Answers (2)

Mostafa EL-Ebzary
Mostafa EL-Ebzary

Reputation: 1

i use it and work successfully

CommentResource::collection($this->comments)->collection->groupBy('star')

Upvotes: 0

Mwthreex
Mwthreex

Reputation: 1059

"You could possibly group the collection once it has been created."

CommentResource::collection($this->comments)->collection->groupBy('star')

credits goes to devcircus with his answer on github

Upvotes: 10

Related Questions