How to display serial number in Laravel?

Created at 21-Jan-2024 , By samar

Serial numbers, often used to uniquely identify or sequence items, can be displayed in Laravel views using a straightforward approach. In this article, we'll explore different methods to achieve this within the context of a Laravel application.

  • Add serial number using Foreach Loop Counter

    One common way to display serial numbers in a Laravel view is by utilizing the loop counter. You can define the counter variable and set as post increment to increase counter for serial number.

    @php($i = 1)
    <thead>
        <th>Sr.no</th>
        <th>Name</th>
        <th>Email</th>
    </thead>
    <tbody>
        @foreach ($users as $user)
        <tr>
            <td>{{ $i++ }}</td>
            <td>{{ $user->name }}</td>
            <td>{{ $user->email }}</td>
            <td>{{ $user->created_at }}</td>
        </tr>
        @endforeach
    </tbody>
    
  • Display serial number for records after using pagination in Laravel

    When you're using pagination in Laravel to display records, you can still display serial numbers for records after moving one page to another page. Here is the simple method $users->firstItem() + $index to display the serial number after using pagination in Laravel.

    <table>
    <thead>
       <th>Sr.no</th>
       <th>Name</th>
       <th>Email</th>
    </thead>
    <tbody>
       @foreach ($users  as $index => $user)
       <tr>
          <td>{{ $users->firstItem() + $index }}</td>
          <td>{{ $user->name }}</td>
          <td>{{ $user->email }}</td>
       </tr>
       @endforeach
    </tbody>
    </table>
    

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.