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!
 
    