1

I have stuck in a silly silly sample of code but i can't find solution. I have this code:

Route::get('/example', function(){
    $arr=[];
    Collection::all()->each(function($collection){
        $arr[]= $collection->id;
    });
    dd($arr);
}); 

and it returns to me an empty array all the time despite the fact that Collection:all() has objects inside. Can someone help me?

billyVal
  • 33
  • 8
  • Think @ThomasEdwards is right. His link also contains the solution. Problem resides on passing the array via `use` – Diogo Santo Dec 13 '18 at 14:30
  • While the 'duplicate' thread does answer the direct question, the spirit of this question is, how to properly use a Collection to get the expected result. It also doesn't explain anything about how Collection Closures actually get re-bound to the Collection class so that it _can_ manipulate the `$items` property. @kakavia, take a look at the `transform()` method. It's basically like `map()`, but manipulates the original array instead of producing a new one. https://laravel.com/docs/5.7/collections#method-transform – kmuenkel Dec 13 '18 at 14:37
  • Thanks all of you for the help! It was actually a scope problem that i didn't know about it. – billyVal Dec 13 '18 at 14:45
  • @Claymore Thanks for the indication. I don't actually want to use any of my code anywhere or split it or whatever, i only had the curiosity why this doesn't work. I didn't know that this happens with anonymous function callbacks. – billyVal Dec 13 '18 at 14:48

1 Answers1

1

In the each section you define function which make it with new scope for the variable.

Try the use of PHP function as:

Route::get('/example', function(){
    $arr=[];
    Collection::all()->each(function($collection) use (&$arr){
        $arr[]= $collection->id;
    });
    dd($arr);
}); 
dWinder
  • 11,597
  • 3
  • 24
  • 39