Gaurav
Gaurav

Reputation: 149

Using groupBy with resource collection laravel

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?

Upvotes: 0

Views: 515

Answers (1)

Ayoub ait
Ayoub ait

Reputation: 219

if you mean clean code

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

Upvotes: 1

Related Questions