[英]Looping through an Eloquent collection and redirecting
我有一個雄辯的boxes
,其中包含一個shipping_cost
值。 我想瀏覽這些框,如果shipping_cost
值為0,則將用戶重定向。 我覺得這應該工作:
$order->boxes->each(function($box)
{
if($box->shipping_cost === 0)
{
return Redirect::route('step-1');
}
});
但事實並非如此。 即使運費為0,也永遠不會重定向。 但是,如果我這樣做:
$order->boxes->each(function($box)
{
if($box->shipping_cost === 0)
{
die('Zero Value');
}
});
如果shipping_cost
為0,則該應用程序將死亡。這對我來說非常混亂,也許我誤解了如何正確地遍歷一個集合? 我設法通過將其轉換為數組並使用foreach
此問題,但這似乎是錯誤的。
問題是您在匿名函數中。 該return
實際上是從閉包返回的,而不是您的控制器函數。
您可以只使用普通的foreach
:
foreach($order->boxes as $box)
{
if($box->shipping_cost === 0)
{
return Redirect::route('step-1');
}
}
或使用contains
Laravel基本集合的內容:
$hasZero = $order->boxes->toBase()->contains(function($box){
return $box->shipping_cost === 0;
});
if($hasZero){
return Redirect::route('step-1');
}
注意: toBase()
很重要,因為toBase()
集合將id作為contains()
參數,而基本集合接受閉包。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.