Laravel 9 – map collect can't scope outside variable array even using use

why map it’s not returning or pushing a values into array i tried to use use function to call my array Emails but its not working here is my logic code

   $emails = []; //emails array

    $students = User::where('role','student')->get();   //10 students email

    $maps = collect($students)->pluck('email'); //collect 10 students email

    $maps->map(function($map) use($emails){
        return  array_push($emails, $map); //push 10 students email to emails array

    return $emails; //test emails array

it is returning empty email array i don’t know why its not working

>Solution :

The code you provided is not working because of the way you are trying to modify the $emails array. The map() function in PHP returns a new collection containing the results of applying the callback function to each item. It does not modify the original collection in place.

To fix this issue, you can try this:

$students = User::where('role','student')->get();   //10 students email
$emails = collect($students)->pluck('email')->toArray();
return $emails;

You don’t need to use a map function here. Using pluck method and converting it to an array should be enough to get an array of emails.
You can also use $students->map->email->toArray() for the same result.

Another thing, keep in mind that if you want to use a variable from the outer scope in a closure (callback function) it needs to be passed as use argument, otherwise the variable will not be accessible.

In your case, you don’t need to use use($emails) as you are creating a new array and returning it.

Leave a Reply