1

I want build a new collection from an existing collection using an each() loop:

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

I am getting the error Undefined variable $test from the code inside the loop. How can I access the $test collection from inside the loop?

Thanks!

TVBZ
  • 564
  • 1
  • 4
  • 15

1 Answers1

2

You can pass data inside the closure by use(). Try this:

$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);
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79