Laravel购物车。如何实现删除方法?

时间:2018-08-22 20:09:38

标签: laravel cart

想要在Laravel中的购物车中添加删除方法。遇到错误

函数App \ Http \ Controllers \ ProductController :: delCartItem()的参数太少,传递了0个且恰好期望1个

我不争论,我理解。我在控制器中的代码

     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');
 }

以及模板中的代码

      @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

路由未通过'$ 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");

我可以在模板中使用

{{$ cart_item [“ id”]}}}

,它将显示id

1 个答案:

答案 0 :(得分:1)

更改路由定义以接受id参数,该参数将作为参数传递给delCartItem控制器方法:

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

不确定是否要使用$cart_item['id']$cart_item['item']['id'],但将链接内的route帮助参数更改为数组:

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