Home > database >  How can I iterate over each record in collection while also manipulating another collection?
How can I iterate over each record in collection while also manipulating another collection?

Time:10-26

Using Laravel I have two models, Prize and Tickets, each prize can only have one ticket associated to it.

When iterating over the Prizes, I want to assign a unique ticket to each one. I do this by randomly selecting one from a collection and then removing it from the collection once assigned.

I've noticed at the each of the each call however some of the Prizes have the same Ticket ID, I suspect the already assigned tickets are not being removed from $tickets within the each loop.

Can someone explain why this is and how I can correctly code this?

$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);
});

CodePudding user response:

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.

  • Related