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)
  3. {{-- ... some code here ... --}}
  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)
  3.     @if($loop->first)
  4.         Here are our users:
  5.         <div>
  6.     @endif
  8.     {{$user->name}}
  10.     @if($loop->last)
  11.         </div>
  12.         That was everyone!
  13.     @endif
  15. @endforeach

$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

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.


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 force non www in htaccess

How to replace values in a string, in JS

How do you launch the PHP interactive shell?

How to check if a object has a static variable defined?

How to block IPv6 IP addresses in .htaccess

How to select all rows for a certain month (or day, year or time), using Eloquent

What is the difference between ( for ... in ) and ( for ... of ) in javascript?

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

301 Redirect a single URL in .htaccess to a new location

How to select what columns to return when calling ::all()