Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading