Loop variable in Laravel foreach
While iterating through a foreach
loop, a $loop
variable will be available inside of your loop.
This variable provides access to some useful bits of information such as it is the first or last iteration through the loop
@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->index
, $loop->parent
, $loop->iteration
or $loop->count
.
Learn more on the official documentation