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

 

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

or

in this case i make array from collection

$labels = [];
$calonFormatur
->each(function ($item, $key) use (&$labels) {
$labels[] = $item->no_urut . '. ' . $item->nama;
})
->toArray();
dd($labels);