Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mehrdad70's avatar

Sum of product prices in the shopping cart

Hi, I have some products in my cart I want the prices of all products together with the deduction of the discount amount together Sum and save in the final price field in the card table. How can this be done?

    public function getPriceAfterApplyCoupon()
    {
        foreach ($this->categories as $category) {
            $coupons = $category->validCoupons();
            if ($coupons->isNotEmpty()) {
                $amount = $this->price;
                $discount = ($amount * $coupons[0]->percent) / 100;
                $total = $amount - $discount;
                foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;
                    //this code not working
                    $cart->final_price  + $total;
                    $cart->save();
                }
                
                return number_format($total);
            }

        }

        return $this->price;

    }
0 likes
18 replies
usmanmalik's avatar

You are not assigning the $total price to $cart->final_price

This should fix it

$cart->final_price += $total;
mehrdad70's avatar

this not work I want to add prices together by deducting the discount price

usmanmalik's avatar

Do you have one cart with multiple products ? or multiple carts ?

usmanmalik's avatar

Ok so I dont know the full context here and its kind of confusing with caregories and coupons looping before you loop over the products. but maybe you should be doing something like this

				$cartTotal = 0;
                foreach ($this->carts as  $cartProduct) {
                    $cartProduct->coupon_id = $coupons[0]->id;
					$cartTotal += $total 
                }
				$this->carts->final_price = $cartTotal ;
				$this->carts->save();  

Ideally you should loop over the cart's product first .. On each iteration apply the discount to product. and add to total .

usmanmalik's avatar

if you are just copy-pasting then it wont. I am just giving you ideas now . You clearly need to refactor this method.

mehrdad70's avatar

I refracted your code but it does not give the desired result This is my shopping cart collection

Illuminate\Support\Collection {#1829 ▼
  #items: array:3 [▼
    0 => App\Course {#1853 ▶}
    1 => App\Course {#1852 ▶}
    2 => App\Course {#1851 ▶}
  ]
}
tomasosho's avatar
foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;
                    //this code should working
                    $cart->final_price = $total;
                    $cart->save();
                }
return number_format($cart->final_price);
mehrdad70's avatar
    public function getPriceAfterApplyCoupon()
    {
        foreach ($this->categories as $category) {
            $coupons = $category->validCoupons();
            if ($coupons->isNotEmpty()) {
                $amount = $this->price;
                $discount = ($amount * $coupons[0]->percent) / 100;
                $total = $amount - $discount;
                foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;
                    //this code should working
                    $cart->final_price = $total;
                    $cart->save();
                }
                return number_format($cart->final_price);
            }
        }

        return $this->price;
    }
tomasosho's avatar

in your table, i take it that final price is the price for an item yes or is it the total price?

mehrdad70's avatar

This is how my card table is structured

        Schema::create('carts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('coupon_id')->nullable()->constrained('coupons')->cascadeOnDelete();
            $table->string('status');
            $table->integer('price')->default(0);
            $table->integer('final_price')->default(0);
            $table->dateTime('expired_at');
            $table->timestamps();
        });

        Schema::create('cart_course', function (Blueprint $table) {

            $table->foreignId('cart_id')->constrained('carts')->cascadeOnDelete();
            $table->foreignId('course_id')->constrained('courses')->cascadeOnDelete();
        });
usmanmalik's avatar

maybe you need to move return out of foreach

public function getPriceAfterApplyCoupon()
    {
        foreach ($this->categories as $category) {
            $coupons = $category->validCoupons();
            if ($coupons->isNotEmpty()) {
                $amount = $this->price;
                $discount = ($amount * $coupons[0]->percent) / 100;
                $total = $amount - $discount;
				$cartTotal = 0;
                foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;
                    //this code not working
                    $cartTotal = $cart->final_price + $total;
                }
         	 }
        }

		return $cartTotal;
    }

...
1 like
tomasosho's avatar

if you're trying to get the total price, use this

mehrdad70's avatar

I have a collection of courses on my card Some of these courses are discounted Some others do not have a discount Now I want to add the prices of these courses together and save them in the final price field on the card

usmanmalik's avatar

so thats why i recommended that you start with a foreach loop on cart

	foreach($this->cart as $cartItem) { 
		$cartTotal = 0;
		
		// check if this cart Item has discount 

		// check for discount coupons
		// if yes . Apply the discount 
		
		// $cartItem->price = $cartItem->price() - $discount;
		
		// Add total to $cartTotal 
		// $cartTotal += $cartItem->price

	} 
	// outside the loop
	return $cartTotal ; 

Please or to participate in this conversation.