Framework: Cannot use groupBy in API resource

Created on 19 Oct 2019  路  1Comment  路  Source: laravel/framework

  • Laravel Version: 6
  • PHP Version: 7.3
  • Database Driver & Version: Mysql 5.7

Description:

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.

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')

>All comments

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')

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JamborJan picture JamborJan  路  3Comments

shopblocks picture shopblocks  路  3Comments

kerbylav picture kerbylav  路  3Comments

iivanov2 picture iivanov2  路  3Comments

YannPl picture YannPl  路  3Comments