Fateh Alrabeai
Fateh Alrabeai

Reputation: 730

how to calculate the total of an order by multiplying the item price with it's quantity using laravel api?

I'm sending a post request using post man(as a test) which contains the following json format:

{

    "place_id": 2,

    "items": [
        {
            "id": 9,
            "quantity": 5
        },
        {
            "id": 8,
            "quantity": 3
        },
           {
            "id": 5,
            "quantity": 2
        }
    ]

}

Now, before the customer confirms his order, I need to make some calculations. Each item has its own price, and I want to calculate the total of each item (price * quantity) but I got a little bit confused on how to do that.

This is my Code (attempt). it gave me the sum of prices But couldn't figure out how to calculate each item's (price * quantity):

     $items = $request->input('items',[]);

       $item_array = [];

        foreach ($items as $key=>$item)
        {
            $item_array[$key] = $item['id'];
        }

        $itemsPriceTotal = Item::whereIN('id',$item_array)->sum('price');
        $itemsPriceTotal =(int)($itemsPriceTotal);

Upvotes: 0

Views: 1510

Answers (2)

Jairus
Jairus

Reputation: 846

I would leverage the model mutators.

See https://laravel.com/docs/5.8/eloquent-mutators:

/**
 * Get the user's full name.
 *
 * @return string
 */
public function getTotalCost()
{
    // Example: $qty = SomeModel::Find()->where(['id' =. $this->id])->one()

    return $this->qty * $this->price;
}

Then use $model->totalCost

Upvotes: 0

alortee
alortee

Reputation: 101

$reqItems = $request->input('items');

// associative array of item ids and their respective quantities
$itemIdsQtys = [];

foreach($reqItems as $reqItem) {
  $itemIdsQtys[$reqItem['id']] = $reqItem['quantity'];
}

// get array of item ids and fetch their respective models
$ids = array_keys($itemIdsQtys);
$itemModels = Item::find($ids);

// calculate total
$priceTotal = 0;
foreach($itemModels as $model) {
  $subtotal = $model->price * $itemIdsQtys[$model->id];
  $priceTotal += $subtotal;
}

return $priceTotal;

Upvotes: 3

Related Questions