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

A list of operators on Eloquent's where() method

How do you run a PHP script from the command line?

How to query mysql using PDO in PHP?

How to see all of the options for an artisan command?

What are PHP's PSRs?

How to replace values in a string, in JS

How to reverse htmlentities() / What is the opposite of htmlentities()?

How do you launch the PHP interactive shell?

How to get table column names from a database table in Eloquent?

How to merge/concat two arrays together in JS?