Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

untymage's avatar

How change structure of json when using groupBy in resource API

When i try passing a collection with groupBy method to the resource class it doesnt accept the key of groupby ,So how to deal with grouping in api resources ?

public function toArray($request)
{
    return [
        'column'  => ModelResource::collection($this->relationship->groupBy('THISCOLUMN')),
    ];
}


Property [THISCOLUMN] does not exist on this collection
0 likes
1 reply
untymage's avatar

Anyone could help me ? In resource collection how to change structure of json that grouped by a specific key ? for example this would work:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'posts' => PostResource::collection($this->posts),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

with this :

Route::get('/user', function () {
    return UserResource::collection(User::all());
});

But as soon i use groupBy in the collection it fails:

Route::get('/user', function () {
    return UserResource::collection(User::get()->groupBy('name'));
});

// Error: Property [name] does not exist on this collection

Please or to participate in this conversation.