Home > front end >  Why does my forget() method not remove object from collection?
Why does my forget() method not remove object from collection?

Time:10-26

I have a collection of "Tickets", using the random collection utility method I select one from the list. The "Tickets" collection should now remove (or forget) that randomly selected ticket so I can further process that collection. Using the forget method doesn't appear to do what is described in the documentation or (more likely I'm missing something).

Can someone spot whats wrong in my code?

$tickets = Tickets::all();
$total_winners = 5;
$selected_tickets = $tickets->random($total_winners);
$jackpot_winner = $selected_tickets->random();
$selected_tickets->forget($jackpot_winner->id); // this line should remove the $jackpot_winner

When I print the contents of $selected_tickets on lines 3 and lines 5, they have the exact same items, including the $jackpot_winner.

CodePudding user response:

Forget function uses the collection key not the id from the model. To achieve what you want you may use this method:

$selected_tickets = $selected_tickets->except($jackpot_winner->id);

https://laravel.com/docs/8.x/collections#method-except

  • Related