Dynamic Row Number in Laravel Blade

I want a dynamic number of rows in a table like this.

number name 1 Devy 

This template is my click.

 <thead> <th>number</th> <th>name</th> </thead> <tbody> @foreach ($aaa as $value) <tr> <td></td> <td>{{$value->name}}</td> </tr> @endforeach </tbody> 

How to do it?

+5
source share
7 answers

It is right:

  @foreach ($collection as $index => $element) {{$index}} - {{$element['name']}} @endforeach 

And you have to use index + 1 because the index starts at 0.

Using source PHP in a view is not the best solution. Example:

 <tbody> <?php $i=1; @foreach ($aaa as $value)?> <tr> <td><?php echo $i;?></td> <td><?php {{$value->name}};?></td> </tr> <?php $i++;?> <?php @endforeach ?> 

in your case:

 <thead> <th>number</th> <th>name</th> </thead> <tbody> @foreach ($aaa as $index => $value) <tr> <td>{{$index}}</td> // index +1 to begin from 1 <td>{{$value}}</td> </tr> @endforeach </tbody> 
+6
source

Use a counter and increase its value in a loop:

 <thead> <th>number</th> <th>name</th> </thead> <tbody> <?php $i = 0 ?> @foreach ($aaa as $value) <?php $i++ ?> <tr> <td>{{ $i}}</td> <td>{{$value->name}}</td> </tr> @endforeach </tbody> 
+3
source

Use the $ loop variable

link to this link Loop Variable

+2
source

Just take the variable before foreach() as $i=1 . And the increment $i before foreach() ends. So you can echo $i in your desired <td></td>

0
source

try the following:

 <thead> <th>number</th> <th>name</th> </thead> <tbody> @foreach ($aaa as $index => $value) <tr> <td>{{$index}}</td> <td>{{$value}}</td> </tr> @endforeach </tbody> 
0
source

Starting with Laravel 5.3, it has become much easier. Just use the $ loop object from this loop. You can access $ loop-> index or $ loop-> iteration. Check this answer: https://laracasts.com/discuss/channels/laravel/count-in-a-blade-foreach-loop-is-there-a-better-way/replies/305861

0
source

Try the $loop->iteration variable $loop->iteration .

''

 <thead> <th>number</th> <th>name</th> </thead> <tbody> @foreach ($aaa as $value) <tr> <td>{{$loop->iteration}}</td> <td>{{$value}}</td> </tr> @endforeach </tbody> 

''

0
source

All Articles