Posts Learn Components Snippets Categories Tags Tools new About
/

Using Laravel $loop Variable In Foreach

Access the loop variable inside foreach to get the information of the particular loop such as loop index and first/last item

Created on Jul 05, 2021

168 views

When looping a variable using "foreach" directive, you can access the "$loop" variable to get some information about the iteration. This is very useful when it comes to present the data such as having different loop styling through the "even", "odd" data and etc.

@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

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Using Laravel $loop Variable In Foreach

)