In a function I have, I'm trying to iterate over a collection of ids and through each iteration, add the result of a method call for that id. However, nothing I've tried seems to work, but I can get it to work with a normal closure.
private function getFormData(Collection $requests): array
{
$assetDeploymentTypes = [];
$requests->pluck('family.school_id')
->unique()
// ->each(function ($id) use (&$assetDeploymentTypes) {
// This works since I can pass the variable in by reference
// $assetDeploymentTypes[$id] = app(AssetDeploymentTypeRepository::class)->deployableTypes($id, ['id', 'name']));
// });
// This doesn't because I can't find a way to pass it by reference
->each(fn ($id) => $assetDeploymentTypes[$id] = app(AssetDeploymentTypeRepository::class)->deployableTypes($id, ['id', 'name']));
dd($assetDeploymentTypes); // Shows empty array
}
Maybe I'm just misunderstanding the uses of arrow functions, but it would be nice to write it this way. I've also tried writing it like (fn& ($id) => ...) like seen here: https://stitcher.io/blog/short-closures-in-php, but then I get the error of "Only variable references should be returned by reference".
mapWithKeys didn't exactly work the way I expected it to, but I think that was because I just had a collection of ids. Combining ->keyBy(fn ($id) => $id) and map, I was able to get it to work correctly though.