Reputation: 4332
I am not fully understanding Laravel Collections. I need to know how save external values while iterating through a Lavavel Collection using the each(function(n){})
For example:
static public myFunction($laravelCollection) ={
$arr=[];
$laravelCollection->each(function($a){
$arr[]=$a
});
return $arr
}
...
$exampleArr = SomeClass::myFunction($aCollection);
var_dump($exampleArr);
//desired results: the var_dump of the collection
It seams that $arr inside of the each function is local to the function. How can I accomplish the above? I realize that if it was NOT a static function, I could simply use a $this->arr instead, but I need to do the above using a static function.
Upvotes: 0
Views: 136
Reputation: 8947
Modifying a variable inside a laravel collection, you will have to use use()
method with reference &
.
$arr = [];
$laravelCollection->each(function($a) use(&$arr) {
$arr[] = $a;
});
Or even better, since you are simply converting your collection into an array:
$arr = $laravelCollection->toArray();
Check out the collection docs.
Upvotes: 3