Loop variable in laravel

In Laravel's Blade templates, the $loop variable provides several properties that can be useful beyond just first and last. Here are the additional properties you can use:


  1. $loop->index: The current iteration index (0-based).

    • Example:
      @foreach ($items as $item)
          <div>{{ $loop->index }}: {{ $item->name }}</div>
      @endforeach
      
  2. $loop->iteration: The current iteration (1-based).

    • Example:
      @foreach ($items as $item)
          <div>Item {{ $loop->iteration }}: {{ $item->name }}</div>
      @endforeach
      
  3. $loop->count: The total number of items in the loop.

    • Example:
      @foreach ($items as $item)
          @if ($loop->last)
              <div>This is the last item out of {{ $loop->count }}: {{ $item->name }}</div>
          @endif
      @endforeach
      
  4. $loop->remaining: The number of items remaining in the loop.

    • Example:
      @foreach ($items as $item)
          <div>{{ $loop->remaining }} items remaining.</div>
      @endforeach

Conclusion

Correct your coding and programming skills to achieve more.