How to filter elements in a collection based on a condition in illuminate/collections?

In Illuminate/Collection, you can use the filter method to filter elements in a collection based on a condition. Here's how you can do it:

  1. First, make sure you have the Illuminate/Collection package installed in your project. You can install it via Composer by running the following command:

    composer require illuminate/collections
  2. In your PHP file, import the necessary classes:

    use Illuminate\Support\Collection;
  3. Create a collection with the elements you want to filter:

    $collection = collect([1, 2, 3, 4, 5]);
  4. Use the filter method and pass a closure that defines the condition for filtering:

    $filtered = $collection->filter(function ($item) { return $item % 2 == 0; // Filter even numbers });

    In this example, the closure checks if an item is divisible by 2 without a remainder, thus filtering even numbers.

  5. The filter method will return a new collection containing the filtered elements. You can iterate over this collection or perform any other operations as needed:

    $filtered->each(function ($item) { echo $item . "\n"; });

    This code simply echoes each filtered item.

That's it! You have successfully filtered elements in a collection based on a condition using Illuminate/Collection.