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 set infinite execution time in a PHP script

How to convert a string to an array of it's characters in PHP?

How to use subdomains as parameters in your routes (or in your web.php file)

How to create random numbers in JS?

Point all requests to one PHP file

How to get the type of a variable in JS?

How to force gzip compression in Apache with .htaccess

What is an example of an object literal?

How to block IP addresses in Apache by using regular expressions (regex) in .htaccess

How to make Apache force download of files (in .htaccess)