使用laravel crinsane推车在购物车中搜索物品

时间:2017-06-04 19:03:02

标签: php laravel laravel-5 shopping-cart

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

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

查看

fun main(args: Array<String>) {
    fun nextTwo(...) {}

    nextTwo(...)
}

路线

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

购物车内容集

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 } ] }` 查找ID为1(香蕉)的购物车项目?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

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

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

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

如果您想在此Closure中使用$request变量,则必须use()

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

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

答案 1 :(得分:0)

希望这对某人也有帮助。

尝试通过where()之类的函数进行查找-

Cart::content()->where('id', $id);

id是您要搜索的项目ID。

找到here