Skip to main content
Quick Tip

$loop variable in foreach

Inside of foreach loop, check if current entry is first/last by just using $loop variable.

@foreach ($users as $user)
@if ($loop->first)
This is the first iteration.
@endif
 
@if ($loop->last)
This is the last iteration.
@endif
 
<p>This is user {{ $user->id }}</p>
@endforeach

There are also other properties like $loop->iteration or $loop->count. Learn more on the official documentation.

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

How to Structure Laravel 13 Projects

16 lessons
1 h 32 min read

[NEW] NativePHP v3: Create Mobile Apps with Laravel

9 lessons
53 min

[NEW] Laravel AI SDK: 6 Practical Examples

9 lessons
1 h 02 min

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.