giwrgos's avatar

How to add indexing on loop (Blade) with pagination

Hello, I have a list of objects that I have selected with the pagination function. I want to add an index number on the table during the loop. So on the first page to be like 1-10 (if the pagination is 10), on the second page (11-21) and so one for the other pages. If i use foreach with key and value the key always starts from 0 on any page. Does anyone know how i can add indexing on the pagination?

0 likes
6 replies
willvincent's avatar

You should be able to access the first/last item value on the paginator instance.. Though this seems to be undocumented, by looking at the code firstItem() and lastItem() should be available.

For this example, lets say you are paginating a list of users..

In your controller you did something like this:

    $users = App\User::paginate(10);
    return view('userlist')->with(compact('users'));

In your view you could do something like this:

<h3>User List</h3>
<h4>Showing {{ $users->firstItem() }} - {{ $users->lastItem() }}</h4>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Operations</th>
    </tr>
  </thead>
  <tbody>
  @foreach ($users as $user)
    <tr>
      <td>{{ $user->name }}</td>
      <td>{{ $user->email }}</td>
      <td>
        <ul>
          <li><a href="/user/{{ $user->id }}/edit">Edit</a></li>
          <li><a href="/user/{{ $user->id }}/delete">Delete</a></li>
        </ul>
      </td>
    </tr>
  @endforeach
  </tbody>
</table>

{!! $users->render() !!}
giwrgos's avatar

Hello @willvincent, thanks for your reply. basically this is what I'm trying to achive

# Name Email Role Status Registered Action @forelse($users as $user) 1 {{{ $user->name }}} {{{ $user->email }}} Admin Active {{{ date("d-m-Y", strtotime($user->created_at)) }}} Edit @empty No users have been found. @endforelse # Name Email Role Status Registered Action {!! $users->render() !!}

the 1 to be auto increment based on the page that you are viewing

in case is hard to be read : http://pastebin.com/U4nZJKBN

willvincent's avatar
Level 54

Ok, so..

@forelse ($users as $index => $user)
//... snip ...
<td>{{ $index + $users->firstItem() }}</td>
//..snip..
2 likes
willvincent's avatar

@firemaps yes, of course.. because $index is the row number in that result set.. based on a offset & limit query. And was kind of the entire point of the post -- how to show which users were being shown on a given page of a paginated list. ;)

Please or to participate in this conversation.