Reputation: 730
I'm trying to multiply each item price with quantity inside array. this is the request I get from the mobile through api : I used dd($request->all());
array:2 [
9 => "4"
8 => "6"
]
//where(9,8) are the item ids and 4,6 are the quantities
$req = $request->all();
$items= [];
foreach ($req as $key => $value){
$items[] = [
"item_id" =>$key ,
"quantity" =>$value ,
];
}
$ids= [];
foreach ($req as $key => $value){
$ids[] = $key;
}
$qunts = [];
foreach ($req as $key => $value){
$qunts[] = (int)$value;
}
$items = Item::whereIn('id',$ids)->get();
//here I'm trying to mutiply each item price with it's quantity comming from the request
$priceTotal = 0;
foreach($items as $item) {
$subtotal = $item->price * $qunts;
$priceTotal += $subtotal;
}
Upvotes: 0
Views: 50
Reputation: 3972
You could do it in this way.
foreach($items as $key => $item) {
$subtotal = $item->price * $qunts[$key];
$priceTotal += $subtotal;
}
Upvotes: 1
Reputation: 6388
You are not using the id of the item to get the quantity, do it in this way
foreach($itemModels as $model) {
$priceTotal += $model->price * $req[$model->id];
}
Upvotes: 1