php - How to Sum Price of Array of Products with their quantities in Laravel
one text
Solution:
Your 'request' looks like json so first we have to transform it to an object or array using json_decode
.
$json = '[{"product_id": 14, "quantity": 1}, {"product_id": 18, "quantity": 1}, {"product_id": 15, "quantity": 1}]';
$collection = collect(json_decode($json));
$totalPrice = Product::query()
->select('id', 'price')
->whereIn('id', $collection->pluck('product_id')
->cursor() // we don't really need to load the models in memory.
->reduce(function ($accumulated, $product) use ($collection) { // reduce the collection to a single value
return $accumulated + ( $product->price * $collection->firstWhere('product_id', $product->id)->quantity );
}, 0); // set initial $accumulated is 0
Or using shorthand closures
$totalPrice = Product::query()
->select('id', 'price')
->whereIn('id', $collection->pluck('product_id')
->cursor()
->reduce(fn($a, $p) => $a + ( $p->price * $collection->firstWhere('product_id', $p->id)->quantity ), 0);
Source