I am trying to calculate pagination:
var pagination = {
total: result.length,
per_page: itemsPerPage, // required
current_page: currentPage, // required
last_page: users.length / itemsPerPage, // required
from: (itemsPerPage * pageNumber) + 1,
to: itemsPerPage * (pageNumber + 1) //required
};
Let say the result length is 2, itemsPerPage is 5, currentPage is 1, I got this:
total: 2
per_page: 5
current_page: 1
last_page: 0.4
from: 6
to: 10
I think something is not right.
total_items / 10 should give you the number of pages. You also need to consider remainder of the division (total_items % 10). So total pages would be total_items / 10 and 1 more in case remainder is > 0.
$offset = ($page - 1) * $items_per_page; Then replace the $page accordingly.
The paginate function accepts the following parameters: totalItems (required) - the total number of items to be paged. currentPage (optional) - the current active page, defaults to the first page. pageSize (optional) - the number of items per page, defaults to 10.
Create dynamic pagination links. Allows you to truncate as well as call a function on page change.
To round for the max value, you can use Math.ceil
on last_page
.
The items per page can be static, manually defined. Then, from
can be ((currentPage - 1) * itemsPerPage) + 1
.
Then it can be currentPage * itemsPerPage
. Eg if the current page is 1, then 1 * 5 = 5, if its the second page it will be: 2 * 5 = 10. Look below for an example:
var pagination = {
total: result.length,
per_page: itemsPerPage,
current_page: currentPage,
last_page: Math.ceil(result.length / itemsPerPage),
from: ((currentPage -1) * itemsPerPage) + 1,
to: currentPage * itemsPerPage
};
Total = 15;
per_page = 5;
currentPage = 1;
last_page = truncate (15 / 5) = 3;
from: ((1-1) * 5) + 1 = 1 //first page
((2-1) * 5) + 1 = 6 //second page
to: 1 * 5 = 5 //first page
2 * 5 = 10 // second page
From 1 to 5 // first page
From 6 to 10 // second page
From 11 to 15 // last page
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With