How to loop collection object in laravel?

by darrion.kuhn , in category: PHP CMS , 11 days ago

How to loop collection object in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 10 days ago

@darrion.kuhn 

In Laravel, you can loop through a collection object using the foreach method or by using Blade template syntax. Here are a few examples:


Using the foreach method:

1
2
3
4
5
$users = User::all();

foreach ($users as $user) {
    echo $user->name;
}


Using Blade template syntax:

1
2
3
@foreach ($users as $user)
    {{ $user->name }}
@endforeach


You can also use the each method to loop through a collection object and print each item:

1
2
3
@foreach ($users->each as $user)
    {{ $user->name }}
@endforeach


These are just a few examples of how you can loop through a collection object in Laravel. You can also use other methods provided by the Laravel Collection class to manipulate and loop through the data as needed.