A tutorial for displaying continuous numbering of collection items on all pagination pages in a Laravel project.
🌍 The French version of this publication : Pagination Laravel : Afficher une numérotation continue des éléments par page
Pagination in Laravel is a mechanism for dividing data into several pages to facilitate presentation and navigation when there are a large number of results.
Let’s consider a collection of publications or $posts
that we retrieve and paginate in the controller’s index method to display 100 per page:
public function index()
{
$posts = Post::paginate(100);
return view("posts.index", compact('posts'));
}
On the view resources/views/posts/index.blade.php
we can display 100 posts per page and present the links of the different pages of the pagination like this:
@extends('layouts.app')
@section('content')
<table>
<thead>
<tr>
<th>No.</th>
<th>Title</th>
</tr>
</thead>
<tbody>
@foreach ($posts as $post)
<tr>
<td></td>
<td></td>
</tr>
@endforeach
</tbody>
</table>
@endsection
In this source code, $loop->iteration
displays the iteration number inside the loop and $posts->links()
displays the pagination links.
But notice, for each individual page the iteration starts at 1. This means that if we’re on page 2, the first iteration of that page will be considered the first iteration in the whole pagination.
If we want to display continuous numbering on all pages of a pagination, we can combine the number of elements per page, the current page number and the current iteration:
@foreach ($posts as $post)
<tr>
<td></td>
<td></td>
</tr>
@endforeach
In this source code we have :
-
$posts->perPage()
: number of elements per page -
$posts->currentPage()
: current page number
By multiplying the number of elements per page by the current page number minus one, we obtain the starting index for that page. By adding $loop->iteration
, we obtain the continuous index for each element of the paginated collection.
So even if you go from page 1 to page 2, the numbering continues from the last index on the previous page.
Take care! 😎
Laravel News Links