Skip to content
Advertisement

How to automatically number each row in a table in laravel?

Please I want to automatically number each row when data is displayed from the database. Something like this

<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
  </tbody>
</table>

so each row is numbered in ascending order from 1 to n depending on the data available in the database. How do I properly do that. Any Help please am new in laravel

Advertisement

Answer

If you are using blade, the laravel’s automatically generated $loop variable might help. Like this:

<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    @foreach($items as $item)
    <tr>
      <th scope="row">{{ $loop->iteration }}</th>
      <td>{{ $item->first_name }}</td>
      <td>{{ $item->last_name }}</td>
      <td>@{{ $item->username }}</td>
    </tr>
    @endforeach
  </tbody>
</table>

You can find documentation here: https://laravel.com/docs/8.x/blade#the-loop-variable

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement