@foreach ($posts as $post) @if ($loop->first) This is the first iteration. @endif @if ($loop->last) This is the last iteration. @endif <p>This is post {{ $post->id }}</p> @endforeach
There are several other properties and below are the ones provided by Laravel.
Available Property
Below are the available properties provided by the $loop variable.
- $loop->index - The index of the current loop iteration (starts at 0).
- $loop->iteration - The current loop iteration (starts at 1).
- $loop->remaining - The iterations remaining in the loop.
- $loop->count - The total number of items in the array being iterated.
- $loop->first - Whether this is the first iteration through the loop.
- $loop->last - Whether this is the last iteration through the loop.
- $loop->even - Whether this is an even iteration through the loop.
- $loop->odd - Whether this is an odd iteration through the loop.
- $loop->depth - The nesting level of the current loop.
- $loop->parent - When in a nested loop, the parent's loop variable.
For a nested loop, you can use $loop->parent to access the outside loop.
@foreach ($posts as $post) @foreach ($posts->comments as $comment) @if ($loop->parent->first) This is the first iteration of the parent loop. @endif @endforeach @endforeach
Leave a reply