In Laravel, a Collection
is a class that provides a convenient wrapper for a PHP array. It provides a variety of methods for working with arrays, including methods for filtering, transforming, and sorting the elements in the collection.
One of the methods available in the Collection
class is each
, which allows you to iterate over the elements in the collection and perform some action on each element. Here is an example of how to use each
:
$collection = collect([1, 2, 3, 4]);
$collection->each(function ($item) {
echo $item;
});
This will output the numbers 1 through 4 on separate lines.
The foreach
loop is a built-in PHP language construct that allows you to iterate over an array or an object that implements the Traversable
interface. You can use the foreach
loop with a Collection
object like this:
$collection = collect([1, 2, 3, 4]);
foreach ($collection as $item) {
echo $item;
}
This will also output the numbers 1 through 4 on separate lines.
The main difference between each
and foreach
is that each
is a method of the Collection
class, while foreach
is a language construct. Additionally, each
allows you to pass a callback function that will be executed on each element of the collection, while foreach
requires you to specify the loop body directly in the loop statement.
Overall, both each
and foreach
can be used to iterate over a Collection
object in Laravel, and which one you choose will depend on your personal preference and the specific needs of your application.