Laravel 从 $collection->each() 循环中访问变量

Laravel acces variable from inside $collection->each() loop

我想使用 each() 循环从现有集合构建新集合:

$spot = Spot::where('slug', $slug)->first()->load('features.group');

$test = collect();

$spot->features->each(function ($item, $key) {
    $current = collect([
        $item->group->name => $item->name,
    ]);
    $test->mergeRecursive($current);
});
    
dd($test);

我从循环内的代码中收到错误 未定义的变量 $test。如何从循环内部访问 $test 集合?

谢谢!

您可以通过use()在闭包内部传递数据。试试这个:

$spot = Spot::where('slug', $slug)->first()->load('features.group');

$test = collect();

$spot->features->each(function ($item, $key) use(&$test) {
    $current = collect([
        $item->group->name => $item->name,
    ]);
    $test->mergeRecursive($current);
});
    
dd($test);