Search code examples
laravellaravel-blade

Final total not calculating display as 0 using Laravel 11


i am a beginner level of laravel programming my problem is when i add item into the cart all the item added successfully but final total calculation is become 0.what i tried so far i attached the code below. i have attached below the controller and view can you check and solve my problem i attached the photo also. enter image description here

ViewCartController

public function index() 
   { 
       $cart = Cart::where('user_id', Auth::id())->with('items.product')->first();
       $totalCost = 0; 
      if ($cart) { 
           foreach ($cart->items as $item)
               { 
                if (isset($item->total_cost)) { $totalCost += $item->total_cost; 
               } }
}

    return view('pages.cart.view', compact('cart', 'totalCost'));
}

cart view

<div class="container">
<h2>Your Cart</h2>
@if (session('success'))
    <div class="alert alert-success">{{ session('success') }}</div>
@endif
@if (session('error'))
    <div class="alert alert-danger">{{ session('error') }}</div>
@endif
@if ($cart && $cart->items->count() > 0)
<div class="total-cost">

    </div>
    <table class="table">
        <thead>
            <tr>
                <th>Product</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Total</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($cart->items as $item)
                <tr>
                    <td>{{ $item->product->productname }}</td>
                    <td>
                        <form action="" method="POST">
                            @csrf
                            @method('PUT')
                            <input type="number" name="qty" value="{{ $item->qty }}" min="1">
                            <button type="submit" class="btn btn-primary">Update</button>
                        </form>
                    </td>
                    <td>{{ $item->product->price }}</td>
                    <td>{{ $item->product->price * $item->qty }}</td>
                    <td>
                        <form action="{{ route('cart.remove', $item->product->id) }}" method="POST">
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="btn btn-danger">Remove</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
    <h3>Total Cost: ${{ $totalCost }}</h3>
@else
    <p>Your cart is empty.</p>
@endif
</div>

Solution

  • You can try this code instead of your existing code.

    $cart = Cart::where('user_id', Auth::id())->with('items.product')->first();
    $totalCost = 0; 
    if ($cart) { 
          foreach ($cart->items as $item)
          { 
              $totalCost += ($item->product->price * $item->qty); 
          }
     }
     return view('pages.cart.view', compact('cart', 'totalCost'));
    

    Try the above code, I it will work for sure. Make sure your $cart returns expected result.

    Note:- I am including all the points that I have mentioned in the comment section but didn't mention here.

    And if you want to know what has gone with your current code,then do the following.

    public function index() 
       { 
           $cart = Cart::where('user_id', Auth::id())->with('items.product')->first();
           dd($cart->items);
           //$totalCost = 0; 
           //if ($cart) { 
           //    foreach ($cart->items as $item)
           //    { 
           //         if (isset($item->total_cost)) { 
           //            $totalCost += $item->total_cost; 
           //        } 
           //    }
           //}
    
        //return view('pages.cart.view', compact('cart', 'totalCost'));
     }
    

    Comment out your existing code except for the 1st two line which will show you your extracted query-result.And then you can check whether the query-result contain this particular field total_cost.

    ->If you didn't find total_cost then logically your code working well but not as your expectation.

    ->And If you find the total_cost, then there might be some issue with data-type you assigned to the column in your migration-file that I have also mentioned in the comment section.

    -> maintain well structured code i.e place {} prpoerly.

    Try this and let me know.