How to remove elements from a collection in illuminate/collections?

To remove elements from a collection using Laravel's Illuminate/Collections, you can use various methods provided by the Collection class. Here are some methods you can use to remove elements from a collection:

  1. forget($key) - Removes an item from the collection by its key. If the given key does not exist, no changes will be made to the collection.
$collection = collect(['name' => 'John', 'age' => 30, 'city' => 'New York']); $collection->forget('age'); // Result: ['name' => 'John', 'city' => 'New York']
  1. pull($key) - Removes and returns an item from the collection by its key. If the given key does not exist, it will return the default value (null by default).
$collection = collect(['name' => 'John', 'age' => 30, 'city' => 'New York']); $age = $collection->pull('age'); // Result: $age = 30, $collection = ['name' => 'John', 'city' => 'New York']
  1. reject($callback) - Removes items from the collection that don't pass a given truth test. The callback should return true for items that you want to keep.
$collection = collect([1, 2, 3, 4, 5]); $filtered = $collection->reject(function ($value, $key) { return $value < 3; }); // Result: [3, 4, 5]
  1. filter($callback) - Removes items from the collection that don't pass a given truth test. The callback should return true for items that you want to keep.
$collection = collect([1, 2, 3, 4, 5]); $filtered = $collection->filter(function ($value, $key) { return $value >= 3; }); // Result: [3, 4, 5]

Note that these methods return a new modified collection, and the original collection remains unchanged. If you want to modify the original collection, you can assign the modified collection back to the original variable.