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:
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
In your PHP file, import the necessary classes:
use Illuminate\Support\Collection;
Create a collection with the elements you want to filter:
$collection = collect([1, 2, 3, 4, 5]);
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.
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.