循环遍历 Eloquent 集合并重定向

Looping through an Eloquent collection and redirecting

我有一个 eloquent 集合 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 实际上会 return 来自闭包而不是你输入的控制器函数。

你可以使用普通的 foreach:

foreach($order->boxes as $box)
{
    if($box->shipping_cost === 0)
    {
        return Redirect::route('step-1');
    }
}

或使用 Laravel 的基础集合中的 contains

$hasZero = $order->boxes->toBase()->contains(function($box){
    return $box->shipping_cost === 0;
});

if($hasZero){
   return Redirect::route('step-1');
}

注意:toBase() 很重要,因为 Eloquent 集合将 id 作为 contains() 的参数,而基础集合接受闭包。