Home > Mobile >  how to do sum with foreach according to index?
how to do sum with foreach according to index?

Time:07-20

I can't do the sum total_product as I want. So, in the cart it has been selected according to store_id, but still does the sum of all the data in the cart.

Database

enter image description here

Controller

public function index($id)
    {
        $cart = Cart::where('user_id', Auth::user()->id)->where('store_id', $id)->get();
        // $carts = $cart->groupBy(fn ($i) => $i->Product->Store->name);
        // dd($cart);
        $cartdetail = CartDetail::where('user_id', Auth()->user()->id)->get();
        $banks = Payment::all();
        $couriers = Courier::all();
        // dd($carts->first()->store_id);
        return view('customer.shipping', [
            'title' => 'Shipping',
            'carts' => $cart,
            // 'cartdetails' => $cart,
            'banks' => $banks,
            'couriers' => $couriers
        ]);
    }

View

@foreach ($carts as $cartdetail =>$items)
   <strong>Rp{{ number_format($items->sum('total_product'), 0, ',', '.') }}</strong>
@endforeach

dd($carts)

enter image description here

enter image description here

enter image description here

Result = 3,713,100 this wrong, the truth is 3,498,000. How to solve it?

CodePudding user response:

you should explain all tables and relations not just code. explain you need sum what? what column and what condition

CodePudding user response:

send $carts->sum('total_product'); in index function.

  • Related