How to Determine the First and Last Iteration in a Foreach Loop in Laravel
In this lesson, we will see how to determine the first and last iteration in a foreach loop in Laravel, sometimes we want to perform actions on the first or the last element of the array when using foreach so how we can do that?
Use the $loop variable
So, to do that use the $loop variable that holds the first and the last item of the iteration.
@foreach ($users as $user)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
@endforeach