In Illuminate/Collections, the each
method is used to iterate over a collection and perform an action on each item. Here's how you can use it:
Create a collection object:
$collection = collect([1, 2, 3, 4, 5]);
Use the each
method to iterate over the collection:
$collection->each(function ($item) {
// Perform action on each item
echo $item;
});
In the example above, the anonymous function passed to the each
method will be executed for each item in the collection. The current item is passed as an argument to the function.
You can perform any desired action within the function, such as echoing, logging, or performing calculations.
Note: The each
method does not modify the original collection. If you want to modify the collection, you can use the transform
or map
methods instead.
Here's another example using a named function:
function processItem($item)
{
// Perform action on each item
echo $item;
}
$collection = collect([1, 2, 3, 4, 5]);
$collection->each('processItem');
In this example, we define a named function processItem
and pass its name as a string to the each
method. The function will be called for each item in the collection.
That's how you can use the each
method to iterate over a collection and perform an action in Illuminate/Collections.