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

PHP Date commonly used formats

What is the difference between reference and primitive data types types in Javascript?

An overview of every main PHP array function

How to force non www in htaccess

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

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

How do Invokable Controllers work in Laravel?

How to change the order that migrations happen?

How to split a string into an array, in JS

How to query mysql using PDO in PHP?