Home » Php » php – Dynamic number of rows in Laravel Blade

php – Dynamic number of rows in Laravel Blade

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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>

Answer:

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>

Answer:

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>

`

Answer:

Use $loop variable

refer this link Loop Variable

Answer:

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>

Answer:

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>

Answer:

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

Answer:

You can Use it like this in Blade. I hope this will help.

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

Note: {{$index +1}} since $index starts from 0