A deep look into $loop variable in Laravel 5.3

Let’s take a deep look into $loop variable in Laravel 5.3. Its a new features of Laravel 5.3.

# Introduction of $loop Variable

n 5.3, the @foreach directive is getting a bit of a superpower, in the form of a new $loop variable that will be available inside every @foreach loop.

The $loop variable is a stdClass object that provides meta information about the loop you’re currently inside. Take a look at the properties it exposes:

  • index: the 1-based index of the current item in the loop; 1 would mean “first item”
  • remaining: how many items remain in the loop; if current item is first of three, would return 2
  • count: the count of items in the loop
  • first: boolean; whether this is the first item in the loop
  • last: boolean; whether this is the last item in the loop
  • depth: integer; how many “levels” deep this loop is; returns 1 for a loop, 2 for a loop within a loop, etc.
  • parent: if this loop is within another @foreach loop, returns a reference to the $loop variable for the parent loop item; otherwise returns null

Most of this is pretty self-explanatory; it means you can do something like this:

Originally published at www.laravelfeed.com.