2 ways to grab the index from a foreach loop in Blade

If you need to grab the index from a foreach loop in Blade, there are 2 ways that I know of.

My favorite way is just using the $loop variable that Laravel makes available for us whenever using a foreach loop.

1. $loop Variable

The $loop provides a lot of useful information (such as figuring out which is the first or last loop).

But in this case, what we are interested in is $loop->index. This will tell you the current index.

An example would be

@foreach ($posts as $post)
  {{$loop->index}}  // Laravel makes this $loop variable available to us in the blade templates

2. key

The other way is accessing a $key variable like this

@foreach ($posts as $key => $post)


Either method of using the $loop variable or assigning a $key will work. I prefer the $loop variable as it looks more elegant to me.

Want to learn how to code and make money online? Check out CodingPhase (referral link)