php - How can I iterate over each record in collection while also manipulating another collection?
one text
Solution:
Why don't you try adding an ampersand before $tickets on the use:
$prizes = Prize::all()->limit(5)->get();
$tickets = Tickets::all()->limit(5)->get();
// iterate over runner up prizes
$prizes->each(function ($prize, $key) use(&$tickets) {
// select ticket from bag
$winner = $tickets->random();
// assign to prize
$prize->ticket_winner_id = $winner->id;
// remove id from remainder
$tickets = $tickets->except($winner->id);
});
That would say to php that you don't want a copy of that variable and you want to mutate it.
Source