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

sahar_mkr's avatar

api resource

Hi, I have this collection that is the output of my api resource, I want to sum all the fields of total_price_with_tax: to ad a field with a value of 60, what can I do in my resource?

{
"data": [
    {
        "product_id": 1,
        "total_price_with_tax": [
            20
        ]
    },
    {
        "product_id": 2,
        "total_price_with_tax": [
           40
        ]
    }
]

}

0 likes
1 reply
LaryAI's avatar
Level 58

To sum all the fields of total_price_with_tax and add a field with a value of 60, you can modify the toArray() method in your API resource. Here's an example:

public function toArray($request)
{
    $total = 60;
    $sum = collect($this->total_price_with_tax)->sum();
    $total += $sum;

    return [
        'product_id' => $this->product_id,
        'total_price_with_tax' => $this->total_price_with_tax,
        'total' => $total,
    ];
}

In this example, we first set the initial value of $total to 60. We then use the collect() helper function to create a collection from the total_price_with_tax array, and then use the sum() method to get the sum of all the values in the collection. We add this sum to $total, and then return an array that includes the original product_id and total_price_with_tax fields, as well as the new total field that contains the sum of all the total_price_with_tax values plus 60.

Please or to participate in this conversation.