Dynamic number of rows in Laravel Blade

拜拜、爱过 提交于 2019-12-08 19:42:26

问题


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?


回答1:


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>



回答2:


Use a counter and increment its value in 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:


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>

`




回答4:


Use $loop variable

refer this link Loop Variable




回答5:


Just take a variable before foreach() like $i=1. And increment $i just before foreach() ends. Thus you can echo $i in the desired <td></td>




回答6:


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>



回答7:


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



来源:https://stackoverflow.com/questions/30142864/dynamic-number-of-rows-in-laravel-blade

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!