Reputation: 3
I read the doc in https://laravel.com/docs/7.x/queries which has this line
foreach ($users as $user) {
echo $user->name;
}
$users is an object of the Illuminate\Support\Collection class which has $items as its field. So how can they loop through $users which has only one field ( $items ) and stil get all the data of the table?
Upvotes: 0
Views: 264
Reputation: 1105
Users Is an object of type Collection. so it contains lists of items of the model user.
If you take a look at the Illuminate\Support\Collection
class you can see this class implements couple of interfaces ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable
And each of them gives the collection class an ability which you can use it. so the reason you can iterate over the collection because the collection is implementing an iterator Interface. so that gives the ability to iterate over them.
Upvotes: 2