2017-06-04 232 views
0

我试图使用Crinsane Larvel Shopping Cart购物车中的商品。 文档讨论了使用闭包。我不明白所提供的例子。使用laravel crinsane购物车搜索购物车中的商品

我正在使用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', '[email protected]'); 

控制器

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

} 

车的Content Collection

`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(香蕉)的购物车物品?

回答

1

你可以做到这一点就像这样:

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

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

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

如果你想用这个封闭的内部$request变量,你将不得不use()它:

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

当然确保$request->has('id')您尝试访问属性之前。

+0

谢谢。有用 ... – DBoonz