Loctarogar
Loctarogar

Reputation: 620

Laravel cart. How to implement delete method?

Want add delete method to cart in laravel. Get an error

Too few arguments to function App\Http\Controllers\ProductController::delCartItem(), 0 passed and exactly 1 expected

I don't pass argument.I understand it. My code in controller

     public function getAddToCart(Request $request, $id) {
     $product = Product::find($id);
     $oldCart = Session::has('cart') ? Session::get('cart') : null;
     $cart = new Cart($oldCart);
     $cart->add($product, $product->id);
     $request->session()->put('cart', $cart);
     //Session::flush();
     //dd($request->session()->get("cart"));
     return redirect()->route('product.index');
 }
 public function getCart() {
     //Session::flush();
     if (!Session::has('cart')) {
         return view('cart.shopping-cart');
     }
     $oldCart = Session::get('cart');
     $cart = new Cart($oldCart);
     return view('cart.shopping-cart', ['cart' => $cart, 'products' => $cart->items, 'totalPrice' => $cart->totalPrice]);
 }

 public function delCartItem(Request $request, $id){
   $oldCart = Session::has('cart') ? Session::get('cart') : null;
   $cart = new Cart($oldCart);
   $cart->del($product, $product->id);
   $request->session()->put('cart', $cart);
   //dd($request->session()->get("cart"));
   return redirect()->route('product.index');
 }

And code from template

      @foreach($cart->items as $cart_item)
    <h4>Product</h4>
    <?php
     $a = ($cart_item["item"]["price"]*$cart_item["qty"]);
    ?>
    <p> Name  : {{ $cart_item['item']['name'] }}</p>
    <p> Price : {{ $cart_item["item"]["price"]}} / Total: {{ $a }}</p>
    <p> Qty   : {{ $cart_item['qty'] }}</p>

    <a href="{{ route('product.delCartItem', $cart_item['id']) }}">Del item</a>
  @endforeach

@endif

Route dosen't pass '$cart_item['id']'.

Route::get("/add-to-cart/{id}", "ProductController@getAddToCart")->name("product.addToCart");
Route::get("/shopping-cart", "ProductController@getCart")->name("product.shoppingCart");
Route::get("/del", "ProductController@delCartItem")->name("product.delCartItem");

I can use

{{ $cart_item["id"] }}

in template and it will show id

Upvotes: 0

Views: 613

Answers (1)

Seva Kalashnikov
Seva Kalashnikov

Reputation: 4392

Change your route definition to accept the id parameter that will be passed as an argument to delCartItem controller method:

Route::get("/del/{id}", "ProductController@delCartItem")->name("product.delCartItem");

Not sure if you have to use $cart_item['id'] or $cart_item['item']['id'] in your case, but change your route helper argument inside the link to be an array:

<a href="{{ route('product.delCartItem', ['id' => $cart_item['id']]) }}">Del item</a>

Upvotes: 1

Related Questions