在 Laravel-5.4 控制器中只允许来自 foreach 循环的一组数据

Allow only one set of data from foreach loop in Laravel-5.4 controller

如何在Laravel-5.4控制器中只允许数组中的一组数据:

foreach(Cart::content() as $cartitem) {
   if($cartitem->id === $id){
      do something....
   }
}

我只想在 $cartitem->id === $id($id 来自请求)时从 $cartitem 获取数据集,并拒绝来自 $cartitem 的所有其他数据集。数据集可以在数组的任何地方(在任何索引中)找到。

您可以使用 where() 或 eloquent 来实现同样的效果。

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

我建议您在请求中已经从购物车中查询了该特定 ID。这样你就不需要这个 foreach 循环了。

foreach(Cart::content() as $cartitem) {
   if($cartitem->id === $id){
      $cartitem; // this is your item
      break; // break from loop you found it already so stop looping
   }
}

documentation 您可以使用:(returns id = 1 的所有项目)

$cart->search(function ($cartItem, $rowId) {
    return $cartItem->id === 1; // this will return all items with id = 1
});

get by rowId

$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; // this is just demo code
Cart::get($rowId);