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

Sinres's avatar

How to get percent of order statistic by count with groupBy

Hello!

I'm trying to get some data with statistic about order statuses. Currently receives some data with count of specific status grouped by shop_id and status, before that, gets the records filtered by spatie query builder e.g. a date range.

In addition to the status object, apart from wanting to add a percentage of quantity relative to other statuses but I don't know how I can do get all statuses count.

This is my code and and what I would like to receive

        $orders = (new GetFilterSortOrders())();
        $collection = $orders
            ->groupBy('shop_id')
            ->map(function ($row) {
                return [
                    'orderable_name' => $row[0]->orderable_type,
                    'shop_id' => $row[0]->shop_id,
                    'statuses' => $row->groupBy('status')->map(function ($status) {
                        return [
                            'count' => $status->count(),
                            'percent' => ($status->count() / $allStatusesCount) * 100
                        ];
                    })
                ];
            })
            ->paginate(request('perPage') ?? 15);

        return OrderStatisticResource::collection($collection);

Thanks for help!

0 likes
5 replies
Sinres's avatar

Any suggestions after the weekend?

reaz's avatar

So every shop has multiple status, and you would like a total count of all the status?

Sinres's avatar

@reaz Every shop has some orders and each order has status(new_order, declared_to_return, realized, returned, partially_realized). I have to get count and percent( e.g. new_order / all_orders_status * 100 ) of each order status by shop.

reaz's avatar
reaz
Best Answer
Level 5

@Sinres inside you first map , you can probably do this:


->map(function ($row) {
        $allStatusesCount = $row->count();
        return [
            'orderable_name' => $row[0]->orderable_type,
            'shop_id' => $row[0]->shop_id,
            'statuses' => $row->groupBy('status')->map(function ($status) use ($allStatusesCount) {
                return [
                    'count' => $status->count(),
                    'percent' => ($status->count() / $allStatusesCount) * 100
                ];
            })
        ];
    })
1 like

Please or to participate in this conversation.