How to unset (remove) a collection element after fetching it?
Laravel Collection
implements the PHP ArrayAccess
interface (which is why using foreach
is possible in the first place).
If you have the key already you can just use PHP unset
.
I prefer this, because it clearly modifies the collection in place, and is easy to remember.
foreach ($collection as $key => $value) {
unset($collection[$key]);
}
I'm not fine with solutions that iterates over a collection and inside the loop manipulating the content of even that collection. This can result in unexpected behaviour.
See also here: https://stackoverflow.com/a/2304578/655224 and in a comment the given link http://php.net/manual/en/control-structures.foreach.php#88578
So, when using foreach
it seems to be ok but IMHO the much more readable and simple solution is to filter your collection to a new one.
/**
* Filter all `selected` items
*
* @link https://laravel.com/docs/7.x/collections#method-filter
*/
$selected = $collection->filter(function($value, $key) {
return $value->selected;
})->toArray();
Or you can use reject
method
$newColection = $collection->reject(function($element) {
return $item->selected != true;
});
or pull
method
$selected = [];
foreach ($collection as $key => $item) {
if ($item->selected == true) {
$selected[] = $collection->pull($key);
}
}
You would want to use ->forget()
$collection->forget($key);
Link to the forget method documentation