Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic number of rows in Laravel Blade

Tags:

php

laravel

blade

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?

like image 479
ka ern Avatar asked May 09 '15 17:05

ka ern


4 Answers

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>

`

like image 77
Kenneth mwangi Avatar answered Oct 14 '22 01:10

Kenneth mwangi


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>
like image 45
Adnan Avatar answered Oct 14 '22 03:10

Adnan


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

like image 34
Hussaini Mamman Avatar answered Oct 14 '22 02:10

Hussaini Mamman


Use $loop variable

refer this link Loop Variable

like image 29
Unni K S Avatar answered Oct 14 '22 02:10

Unni K S