Beney
Beney

Reputation: 41

How to sum total price from a Many to Many relationship collection in Laravel

Here is the collection withCount

Illuminate\Database\Eloquent\Collection {#12203
     all: [
       App\Product {#12171
         id: 1,
         description: "Test 1",
         price: 600.0,
         applications_count: 314,
       },
       App\Product {#12195
         id: 2,
         description: "Test 2",
         price: 1000.0,
         applications_count: 1129,
       },
       App\Product {#12201
         id: 3,
         description: "Test 3",
         price: 1500.0,
         applications_count: 6,
       },

Tried

$products = Product::withCount('applications')->get();

       return $this->result(
            $products->flatMap(function ($product) {
                return [
                    $product->price => $product->applications_count
                ];
            })->toArray()
        );

I need to find the total of the collection, Basically it should be price * application_count I guess. Please give me an idea.

Upvotes: 1

Views: 1184

Answers (2)

porloscerros Ψ
porloscerros Ψ

Reputation: 5078

You can map the collection to calculate the total price of each product (price * applications_count) and then get the sum of total prices with sum() method:

$products = Product::withCount('applications')->get();

$total = $products->map(function ($product, $key) {
    return $product->price * $product->applications_count;
})->sum();

Collections Available Methods used here:
map()
sum()

Upvotes: 1

Makdous
Makdous

Reputation: 1433

Iterate through each $product in $products and calculate price * application_count then sum it in a variable and return it:

$products = Product::withCount('applications')->get();

$total_price = 0; 

foreach ($products as $product){
        $total_price += $product['price'] * $product['applications_count'];
    }

return $total_price;

Upvotes: 1

Related Questions