php - 使用 laravel crinsane cart 搜索购物车中的商品

标签 php laravel laravel-5 shopping-cart

我正在尝试使用 Crinsane Larvel Shopping Cart 从购物车中获取商品。 该文档讨论了使用闭包。我不明白所提供的示例。

我正在使用 Laravel 5.3,尝试使用 Request 对象中的信息从购物车中搜索商品。这是我的代码:

查看

@foreach($cart as $item)
<td>
    <div>
        <a href='{{url("cart?id=$item->id&add=1")}}'> + </a>
        <input type="text" name="qty" value="{{$item->qty}}" autocomplete="off" size="2">
        <a href='{{url("cart?id=$item->id&minus=1")}}'> - </a>
    </div>
</td>
@endforeach

路线

Route::get('/cart', 'CartController@getCart');

Controller

public function getCart(){

    //increment the quantity
    if (Request::get('id') && (Request::get('add')) == 1) {

        $inputItem = Request::get('id');
        //$rowId = Cart::search(['id' => Request::get('id')]);
        $cartItem = Cart::get($rowId);
        Cart::update($rowId, $cartItem->qty+1);
    }

    //decrease the quantity
    if (Request::get('id') && (Request::get('minus')) == 1) {

        $inputItem = Request::get('id');
        //$rowId = Cart::search(['id' => Request::get('id')]);
        $cartItem = Cart::get($rowId);
        Cart::update($rowId, $cartItem->qty-1);
    }

}

购物车内容收藏

`Collection {#318 ▼
  #items: array:2 [▼
    "027c91341fd5cf4d2579b49c4b6a90da" => CartItem {#319 ▼
      +rowId: "027c91341fd5cf4d2579b49c4b6a90da"
      +id: "1"
      +qty: 1
      +name: "Banana"
      +price: 35.0
      +options: CartItemOptions {#320 ▼
        #items: []
      }
      -associatedModel: null
      -taxRate: 21
    }
    "370d08585360f5c568b18d1f2e4ca1df" => CartItem {#321 ▼
      +rowId: "370d08585360f5c568b18d1f2e4ca1df"
      +id: "2"
      +qty: 7
      +name: "Melon"
      +price: 64.0
      +options: CartItemOptions {#322 ▼
        #items: []
      }
      -associatedModel: null
      -taxRate: 21
    }
  ]
}`

如何使用 Cart::search() 查找 id 为 1(香蕉)的购物车商品?

最佳答案

你可以这样做:

Cart::search(function($cartItem, $rowId) {
    return $cartItem->id == 1;
});

search 方法是 Laravel filter method on collections 的包装器.

闭包只是传递给函数的函数,该函数可能会也可能不会从父函数接收变量作为参数。

如果你想在这个闭包中使用$request变量,你必须use()它:

Cart::search(function($cartItem, rowId) use($request) {
    return $cartItem->id == $request->id;
});

当然,在尝试访问该属性之前,请确保 $request->has('id')

关于php - 使用 laravel crinsane cart 搜索购物车中的商品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44357773/

相关文章:

Laravel 服务提供者从数据库检索数据

php - 在 Laravel 中同时执行多个查询

laravel - Laravel 5 包中依赖注入(inject)的最佳方法

php - php sdk 中按前缀的 Azure 列表 Blob

php - 实时了解用户在我的站点中

php - 用户已存在 Echo - 注册并登录

javascript - 每年在仪表板中显示的数字从 1 开始

Laravel 4 hasMany 带有 WHERE 子句

javascript - 如何升级Vue版本

laravel - 无法在 Laravel 4 中切换语言