Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ArchStanton's avatar

count in a blade foreach loop -is there a better way?

 <?php $pos=1 ?>
             @foreach ($athletes as $athlete)
    
//some html goes here
          
            
<?php print $pos++ ?>
             @endforeach
0 likes
18 replies
veve286's avatar

if $athletes is collection object u can simply use this function. $athletes->count();

2 likes
pmall's avatar
@for ($i = 0; $i < count($athletes); $i++)
    // use $i as index
    // use $athletes[$i]
@endfor
2 likes
AddWebContribution's avatar

You can try below code with $indexKey

@foreach ($athletes as $indexKey => $athlete)
   {{$indexKey}} 
@endforeach 

$indexKey starting with 0, So it should be {{ $indexKey+1 }}

8 likes
Paschal's avatar

Might be late but with Laravel 5.3 I think, Blade templating, you now have a $loop variable inside a loop which is an object of useful properties.

$loop->index returns the current loop index starting from 0 $loop->iteration starts from 1

34 likes
codeNfold's avatar

please read this https://laravel.com/docs/5.4/blade#loops, for me $loop->iteration gets the job done. This increases with the iteration starting from 1.

@foreach ($Users as $user)
   <tr>
      <td>{{$loop->iteration}}</td>
      <td>{{$user->receiver}}</td>
      <td>{{$user->receiver_package}}</td>
      <td>{{$user->payer}}</td>
      <td>{{$user->payer_package}}</td>                                  
      <td>{{$user->created_at}}</td>                                   
   </tr>
 @endforeach
2 likes
azzamumer77's avatar

@codeNfold What if i am using another loop inside this loop, it will then give me repeated iterations again and again. How to resolve it?

herrygallery's avatar

I try this:

In Controller: $author = Author::findOrFail($id);

In View: @foreach ($author->books as $book) @endforeach

Amount of books by this author: {{ count($author->books) }}

lrodriguez's avatar

You can use: $loop->iteration It already counts each iteration.

Please or to participate in this conversation.