-2

Actually i am doing project on laravel 9 and i make add to cart function, but i have 1 problem. I want the title to be in the cart but i can not make it.

My codes are below:

shop.blade.php

             <div class="container">
                            <div class="row">
                                <div class="col-lg-12 col-sm-12 col-12 main-section" style="background-color: #3D464D !important">
                                    <div class="dropdown">
                                        <button type="button" class="btn btn-info" data-toggle="dropdown" style="    margin-top: 26px;
                                        margin-left: 54px;
                                        background-color: #FFD333 !important;">
                                            <i class="fa fa-shopping-cart" aria-hidden="true"></i> Cart <span class="badge badge-pill badge-danger">{{ count((array) session('cart')) }}</span>
                                        </button>
                                        <div class="dropdown-menu">
                                            <div class="row total-header-section">
                                                <div class="col-lg-6 col-sm-6 col-6">
                                                    <i class="fa fa-shopping-cart" aria-hidden="true"></i> <span class="badge badge-pill badge-danger">{{ count((array) session('cart')) }}</span>
                                                </div>
                                                @php $total = 0 @endphp
                                                @foreach((array) session('cart') as $id => $details)
                                                    @php $total += $details['price'] * $details['quantity'] @endphp
                                                @endforeach
                                                <div class="col-lg-6 col-sm-6 col-6 total-section text-right">
                                                    <p>Total: <span class="text-info">$ {{ $total }}</span></p>
                                                </div>
                                            </div>
                                            @if(session('cart'))
                                                @foreach(session('cart') as $id => $details)
                                                    <div class="row cart-detail">
                                                        <div class="col-lg-4 col-sm-4 col-4 cart-detail-img">
                                                            <img src="{{ $details['title'] }}" />
                                                        </div>
                                                        <div class="col-lg-8 col-sm-8 col-8 cart-detail-product">
                                                            <p>{{ $details['name'] }}</p>
                                                            <span class="price text-info"> ${{ $details['price'] }}</span> <span class="count"> Quantity:{{ $details['quantity'] }}</span>
                                                        </div>
                                                    </div>
                                                @endforeach
                                            @endif

CartController.php

                          <?php

         namespace App\Http\Controllers;

           use Illuminate\Http\Request;

          use App\Models\Product;

     class CartController extends Controller
          {
public function cart()
{
    return view('cart');
}

/**
 * Write code on Method
 *
 * @return response()
 */
public function addToCart($id)
{
    $product = Product::findOrFail($id);
      
    $cart = session()->get('cart', []);

    if(isset($cart[$id])) {
        $cart[$id]['quantity']++;
    } else {
        $cart[$id] = [
            "title" => $product->title,
            "quantity" => 1,
            "price" => $product->price,
            "image" => $product->image
        ];
    }
      
    session()->put('cart', $cart);
    return redirect()->back()->with('success', 'Product added to cart successfully!');
}

/**
 * Write code on Method
 *
 * @return response()
 */
public function update(Request $request)
{
    if($request->id && $request->quantity){
        $cart = session()->get('cart');
        $cart[$request->id]["quantity"] = $request->quantity;
        session()->put('cart', $cart);
        session()->flash('success', 'Cart updated successfully');
    }
}

/**
 * Write code on Method
 *
 * @return response()
 */
public function remove(Request $request)
{
    if($request->id) {
        $cart = session()->get('cart');
        if(isset($cart[$request->id])) {
            unset($cart[$request->id]);
            session()->put('cart', $cart);
        }
        session()->flash('success', 'Product removed successfully');
    }
}
  }

cart.blade.php

                  @extends('layout')

               @section('content')
               <table id="cart" class="table table-hover table-condensed">
              <thead>
              <tr>
                 <th style="width:50%">Product</th>
              <th style="width:10%">Price</th>
             <th style="width:8%">Quantity</th>
                 <th style="width:22%" class="text-center">Subtotal</th>
                  <th style="width:10%"></th>
             </tr>
          </thead>
           <tbody>
               @php $total = 0 @endphp
              @if(session('cart'))
                 @foreach(session('cart') as $id => $details)
                   @php $total += $details['price'] * $details['quantity'] @endphp
               <tr data-id="{{ $id }}">
                <td data-th="Product">
                    <div class="row">
                        <div class="col-sm-3 hidden-xs"><img src="{{ $details['image'] }}" width="100" height="100" class="img-responsive"/></div>
                        <div class="col-sm-9">
                            <h4 class="nomargin">{{ $details['name'] }}</h4>
                        </div>
                    </div>
                </td>
                <td data-th="Price">${{ $details['price'] }}</td>
                <td data-th="Quantity">
                    <input type="number" value="{{ $details['quantity'] }}" class="form-control quantity update-cart" />
                </td>
                <td data-th="Subtotal" class="text-center">${{ $details['price'] * $details['quantity'] }}</td>
                <td class="actions" data-th="">
                    <button class="btn btn-danger btn-sm remove-from-cart"><i class="fa fa-trash-o"></i></button>
                </td>
            </tr>
         @endforeach
            @endif
        </tbody>
        <tfoot>
          <tr>
        <td colspan="5" class="text-right"><h3><strong>Total ${{ $total }}</strong></h3></td>
             </tr>
               <tr>
        <td colspan="5" class="text-right">
            <a href="{{ url('/') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> 
          Continue Shopping</a>
            <button class="btn btn-success">Checkout</button>
                 </td>
            </tr>
          </tfoot>
       </table>
      @endsection

      @section('scripts')
      <script type="text/javascript">

       $(".update-cart").change(function (e) {
       e.preventDefault();

         var ele = $(this);

         $.ajax({
        url: '{{ route('update.cart') }}',
        method: "patch",
        data: {
            _token: '{{ csrf_token() }}', 
            id: ele.parents("tr").attr("data-id"), 
            quantity: ele.parents("tr").find(".quantity").val()
            },
             success: function (response) {
           window.location.reload();
                      }
            });
           });

        $(".remove-from-cart").click(function (e) {
       e.preventDefault();

     var ele = $(this);

          if(confirm("Are you sure want to remove?")) {
        $.ajax({
            url: '{{ route('remove.from.cart') }}',
            method: "DELETE",
            data: {
                _token: '{{ csrf_token() }}', 
                id: ele.parents("tr").attr("data-id")
            },
            success: function (response) {
                window.location.reload();
            }
         });
       }
       });

        </script>
      @endsection

I have table named products in database and in this table column 'title' I want to add title in cart, please help!

Gregory
  • 1
  • 1
  • 1
    `$cart[$id] = [ "name" => $product->name, "quantity" => 1, "price" => $product->price, "image" => $product->image ];`.... so there's no "title" property in that cart data, is there? Therefore where do you expect the "title" to be coming from when you try to show that data in the view? I suggest adding an extra property when you're creating the cart data. It's a bit unclear how/why you're stuck with that. – ADyson Aug 25 '22 at 09:01
  • how can i make it? please write code for my example – Gregory Aug 25 '22 at 09:04
  • can you show us the output of dd(session()->get('cart')). And the better way of getting the value from session is session()->get('cart') – Tanvir Ahmed Aug 25 '22 at 09:14

1 Answers1

0

I think you have to replace <img src="{{ $details['title'] }}" /> with <img src="{{ $details['image'] }}" /> as there's no array key title. And you're trying to display an image where you're using the title key

John Zwarthoed
  • 1,239
  • 7
  • 12