I want a dynamic number of rows in a table like this.
number name
1 Devy
This my Blade template.
<thead>
<th>number</th>
<th>name</th>
</thead>
<tbody>
@foreach ($aaa as $value)
<tr>
<td></td>
<td>{{$value->name}}</td>
</tr>
@endforeach
</tbody>
How do I do that?
Try $loop->iteration
variable.
`
<thead>
<th>number</th>
<th>name</th>
</thead>
<tbody>
@foreach ($aaa as $value)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$value}}</td>
</tr>
@endforeach
</tbody>
`
This is correct:
@foreach ($collection as $index => $element)
{{$index}} - {{$element['name']}}
@endforeach
And you must use index+1 because index starts from 0.
Using raw PHP in 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>
Starting from Laravel 5.3, this has been become a lot easier. Just use the $loop object from within a given 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
Use $loop variable
refer this link Loop Variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With