How to use the "reject" method to filter out elements from a collection in illuminate/collections?

To use the "reject" method in the Illuminate/Collections package to filter out elements from a collection, you can follow these steps:

  1. Include the necessary class at the top of your PHP file:
use Illuminate\Support\Collection;
  1. Create a new instance of the Collection class with your collection data:
$collection = new Collection([1, 2, 3, 4, 5]);
  1. Use the "reject" method to filter out elements based on a callback function. The callback function should return true for elements that need to be removed from the collection. For example, let's remove all odd numbers:
$filtered = $collection->reject(function ($value, $key) { return $value % 2 !== 0; });
  1. You can now iterate over the filtered collection using a loop or other Collection methods, or simply dump the result:
$filtered->dump();

This will output the filtered collection without the odd numbers:

array:2 [▼ 0 => 2 3 => 4 ]

Alternatively, you can also assign the filtered collection to a new variable:

$filtered = $collection->reject(function ($value, $key) { return $value % 2 !== 0; });

Now, the $filtered variable will contain the filtered collection.

By using the "reject" method, you can easily filter out elements from a collection based on your custom logic.