Laravel Collection Group By and Sum by Date

  arrays, laravel, laravel-collection, php

I have a collection of data which are required to be processed to be able to generate report

below are the sample of data provided

$arrival_data = [
    [
        "arrival_date" => "09-Dec-2020",
        "total_amount" => "10",
        "total_traveller" => 6
    ],
    [
        "arrival_date" => "09-Dec-2020",
        "total_amount" => "20",
        "total_traveller" => 6
    ],
    [
        "arrival_date" => "10-Dec-2020",
        "total_amount" => "40",
        "total_traveller" => 3
    ]
];

I would like to process the data above so it will group by ‘arrival_date’ and sum the data so that the data will appear like below

$arrival_data = [
    [
        "arrival_date" => "09-Dec-2020",
        "total_amount" => "30", // sum of 10 + 20
        "total_traveller" => 6
    ],
    [
        "arrival_date" => "10-Dec-2020",
        "total_amount" => "40",
        "total_traveller" => 3
    ]
];

i haven’t manage to produce the output intended using laravel collection, the closest i am able to get is as below

{
    "09-Dec-2020": 30,
    "10-Dec-2020": 40
}

using below code

$collection = collect($arrival_data);

$num = $collection->groupBy('arrival_date')->map(function ($row) {
    return $row->sum('total_amount');
});

return $num->toArray();

do laravel collection able to write codes to produce the output as intended or need to use a different method by looping array and processing.

Thank you

Source: Laravel

Leave a Reply