【问题标题】:Laravel cart. How to implement delete method?Laravel 购物车。如何实现删除方法?
【发布时间】:2019-01-29 03:50:07
【问题描述】:

想在 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

【问题讨论】:

  • 如果我使用 $cart_item->id 我得到错误:尝试获取非对象的属性 'id'
  • 您还需要将 Request 对象传递给函数,因为它是第一个参数。
  • 你需要使用$cart_item['id']还是$cart_item['item']['id']?还要添加您的路线代码

标签: laravel cart


【解决方案1】:

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

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    相关资源
    最近更新 更多