Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

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

31 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

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Using Laravel $loop Variable In Foreach

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More