0

I am using Laravel 7.0.

My domain_prices table has price, duration, addPrice columns.

I created DomainPrice model.

Domain price for specific duration is price + addPrice.

But for 5 years duration, I need to sum all prices and all addPrices for 1, 2, 3, 4, 5 years.

I set custom attribute to get totalPrice as following:

public function getTotalPriceAttribute()
{
   return $this->price+$this->addPrice;
}

I wanted to make another custom attribute to get sumPrice as following:

    public function getSumPriceAttribute()
    {
        $sumPrice = 0;
        $prices = $this->where('Duration', '<=', $this->Duration)->get(); // I removed domain filter query here.
        foreach($prices as $price)
        {
            $sumPrice += $price->totalPrice;
        }

        return $sumPrice;
    }

But this didn't return exact results. Please teach me with fancy approach. Thanks.

LoveCoding
  • 1,121
  • 2
  • 12
  • 33

1 Answers1

2

I think you used the wrong variable here when you sum your $sumPrice. you should change $subPrice in foreach loop to $sumPrice

public function getSumPriceAttribute()
{
    $sumPrice = 0;
    $prices = $this->where('Duration', '<=', $this->Duration)->get(); // I removed domain filter query here.
    foreach($prices as $price)
    {
        $sumPrice += $price->totalPrice; // change $subPrice to $sumPrice
    }
    return $sumPrice;
}
Thien Huynh
  • 559
  • 5
  • 13