$loop variable in foreach

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

1@foreach ($users as $user)
2 @if ($loop->first)
3 This is the first iteration.
4 @endif
5 
6 @if ($loop->last)
7 This is the last iteration.
8 @endif
9 
10 <p>This is user {{ $user->id }}</p>
11@endforeach

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

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord