Using groupBy with resource collection laravel

471 Views Asked by At

I am working on api, and using resource to send data. I want to send collection which is grouped by status. So far I have done the following:

public function data(){
    $collection = ModelNameResource::collection(
        ModelName::query()
            ->latest()
            ->get()
    );
    $data = $collection->groupBy('status');
    return $data;
}

Although I have got what I want but want to know if there is the better approach to achieve this?

1

There are 1 best solutions below

0
Ayoub ait On

if you mean clean code

public function data(){
    return ModelNameResource::collection(
        ModelName::query()
            ->latest()
            ->get()
    )->groupBy('status');
}