php - 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.
Answer
Solution:
You can map the collection to calculate the total price of each product (price * applications_count) and then get the sum of total prices withsum()
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()
Answer
Solution:
Iterate through each$product
in$products
and calculateprice * 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;
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the browser (or proxy) sent a request that this server could not understand.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.