Home / Snippets / Using Laravel $loop Variable In Foreach
Using Laravel $loop Variable In Foreach cover

Using Laravel $loop Variable In Foreach

362

3 years ago

0 comments

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
notion avatar

Ahabz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this