Ricardo Plompen
Ricardo Plompen

Reputation: 115

total price of products laravel

I need the sum of prices in my order for my webshop I have this:

  @foreach($order->orderrow as $orderrow)
            {{  $product = $orderrow->product->latest_price->price }}
  @endforeach

this will show all the prices in the order, the order is build with an orderrow here are the products for the order, the prices are in an single table.

there for in the

Product model

public function price() {
    return $this->hasMany(Price::class);
}
public function latest_price() {
    return $this->hasOne(Price::class)->orderBy('date', 'desc');
}

when i try to do the sum for with the latest_price it will get all the prices in my database sum upped

 @foreach($order->orderrow as $orderrow)
            {{  $product = $orderrow->product->latest_price->sum('price') }}
  @endforeach

it will sum up all the prices in the table of price.

Upvotes: 0

Views: 1098

Answers (2)

Rwd
Rwd

Reputation: 35180

One option would be to use the sum() method on the collection:

$totalOrderPrice = $order->orderrow->sum(function ($orderRow) {
    return $orderRow->product->latest_price->price;
});

The above assumes that $order->orderrow is a collection. If it isn't you could simply wrap it with collect(...) to get the same results i.e.:

$totalOrderPrice = collect($order->orderrow)->sum(function ($orderRow) {
    return $orderRow->product->latest_price->price;
});

Upvotes: 1

Makdous
Makdous

Reputation: 1433

You can sum the total price of the $order in the controller then send it with the $order to the view:

 $totalOrderPrice = 0;
 foreach($order->orderrow as $orderrow){
         $totalOrderPrice += $orderrow->product->latest_price->price;
 }
 return view('yourViewName')->with(['totalOrderPrice'=>$totalOrderPrice,'order'=>$order]);

Upvotes: 1

Related Questions