What is the loop variable in a @foreach loop in Blade?

Laravel: What is the loop variable in a @foreach loop in Blade?

If you have the following code in a Blade file:

  1. @foreach(\User::all() as $user)
  2.  
  3. {{-- ... some code here ... --}}
  4.  
  5. @endforeach

You have access to $user (obviously) but also the $loop object.

The $loop object has the following data:

  1. object(stdClass)#290 (8) {
  2.   ["iteration"]=> int(1) // starts at 1 (on first loop)
  3.    ["index"]=> int(0) // starts at 0 (on first loop)
  4.    ["remaining"]=> int(4)
  5.    ["count"]=> int(5)
  6.    ["first"]=> bool(true)
  7.    ["last"]=> bool(false)
  8.    ["depth"]=>int(1)
  9.    ["parent"]=>NULL
  10. }

So if you wanted to do something different for the first or last rows then you could easily do this:

  1. @foreach(\App\User::all() as $user)
  2.  
  3.     @if($loop->first)
  4.         Here are our users:
  5.         <div>
  6.     @endif
  7.  
  8.     {{$user->name}}
  9.  
  10.     @if($loop->last)
  11.         </div>
  12.         That was everyone!
  13.     @endif
  14.  
  15. @endforeach

PropertyDescription
$loop->indexThe index of the current loop iteration (starts at 0).
$loop->iterationThe current loop iteration (starts at 1).
$loop->remainingThe iterations remaining in the loop.
$loop->countThe total number of items in the array being iterated.
$loop->firstWhether this is the first iteration through the loop.
$loop->lastWhether this is the last iteration through the loop.
$loop->depthThe nesting level of the current loop.
$loop->parentWhen in a nested loop, the parent's loop variable.

see more

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about What is the loop variable in a @foreach loop in Blade?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to sort an array of dates and times?

How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

How to check if a user is logged in, inside a blade file?

How to review blog posts (written by other users) before they get published on your WordPress blog?

How to set environmental variables in your .htaccess file

How do you access the php://input stream?

How to order a Laravel hasMany relationship?

What are the SPL Iterators in PHP?

What is camel case?

What are the SPL data structures