If you’ve used Laravel before, you’re probably familiar with the pagination feature. Pagination in Laravel helps you divide a large amount of data into smaller, manageable chunks (pages) to display in the frontend.
For instance, instead of loading all 1000 blog posts at once, Laravel can automatically divide them into pages, like:
- Page 1: Posts 1–20
- Page 2: Posts 21–40
- Page 3: Posts 41–60
…and so on.
But what if you want to use this handy feature outside of Laravel? It turns out you can use Laravel’s illuminate/pagination package in a standalone PHP project.
Let’s dive into how you can set up pagination using Laravel’s illuminate/pagination package without the entire Laravel framework!
What is illuminate/pagination?
The illuminate/pagination package is a part of the Laravel framework, and it’s designed to paginate data. It provides a clean and simple API to paginate results, including:
- Handling the pagination logic (how to calculate the offset, page number, etc.).
- Generating pagination links (e.g., Next, Previous, 1, 2, 3…).
- Handling the current page and total number of pages.
In simple terms, it’s a helper package for dividing large sets of data into pages and generating clickable pagination links.
Steps to Use illuminate/pagination in a Standalone PHP Script
Let’s break down the process into clear steps.
Step 1: Install illuminate/pagination
The first thing you need to do is install the illuminate/pagination package via Composer. If you haven’t already installed Composer, you can get it here.
In your terminal, run the following command:
composer require illuminate/pagination illuminate/support
This command will install the necessary libraries for pagination and some Laravel support classes.
Step 2: Create the PHP Script
Once installed, you can create a PHP script to paginate a simple dataset. Here’s an example:
<?php
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
require_once 'vendor/autoload.php';
echo 'hello form pagination page';
$data = [];
for ($i = 0; $i < 100; $i++) {
$data[] = "Post #" . $i;
}
$currentPage = Paginator::resolveCurrentPage();
$perPage = 10;
$currentData = array_slice($data, ($currentPage - 1) * $perPage, $perPage);
$paginator = new LengthAwarePaginator(
$currentData,
count($data),
$perPage,
$currentPage,
['path' => Paginator::resolveCurrentPath()],
);
// Use Bootstrap style for pagination links (optional, just for styling)
$paginator->setPageName('page'); // This is the query string variable that will hold the page number
$paginator->setPath('/pagination/index.php');
// Display the current page's data
echo "<h2>Page $currentPage</h2>";
echo "<ul>";
foreach ($paginator->items() as $item) {
echo "<li>$item</li>";
}
echo "</ul>";
// Display pagination links (Next, Previous, 1, 2, 3, etc.)
// Since we're not in a Laravel Blade view, manually render simple pagination links:
echo '<div>';
if ($paginator->onFirstPage()) {
echo '<span>Previous</span> ';
} else {
echo '<a href="' . $paginator->previousPageUrl() . '">Previous</a> ';
}
for ($page = 1; $page <= $paginator->lastPage(); $page++) {
if ($page == $paginator->currentPage()) {
echo "<span>$page</span> ";
} else {
echo '<a href="' . $paginator->url($page) . "\">$page</a> ";
}
}
if ($paginator->hasMorePages()) {
echo '<a href="' . $paginator->nextPageUrl() . '">Next</a>';
} else {
echo '<span>Next</span>';
}
echo '</div>';
Breakdown of the Code:
- Autoload Dependencies:
We start by including Composer’s autoloader withrequire 'vendor/autoload.php';. This ensures all the packages we installed are available in our script. - Simulate Data:
We create an array of 100 items (like blog posts). In a real-world case, this data would likely come from a database query. - Get the Current Page:
- We use the
Paginator::resolveCurrentPage()method to get the current page number. Typically, this would come from a URL query parameter (e.g.,page=1).
- We use the
- Pagination Logic:
- We use the
array_slicefunction to grab a chunk of data for the current page. - We then create a
LengthAwarePaginatorinstance to handle pagination logic. The paginator takes the current data for the page, the total number of items, the number of items per page, and the current page.
- We use the
- Generate Pagination Links:
Thelinks()method generates the pagination links. These links allow the user to navigate between pages (Next, Previous, etc.). - Display Data and Links:
- We loop through the
items()method of the paginator to display the current page’s data (e.g., blog posts). - We call
links()to generate the pagination navigation links.
- We loop through the
What Does This Code Do?
When you run this script (e.g., via a web browser), it simulates a pagination system that displays 10 items per page from the $data array.
For example, if you’re on Page 1, it will show:
- Post #1 to Post #10
If you go to Page 2 (e.g., /pagination_test.php?page=2), it will display:
- Post #11 to Post #20
And the pagination links (Next, Previous, 1, 2, 3, etc.) will appear at the bottom to help you navigate between pages.
Understanding Key Classes Used
- LengthAwarePaginator:
This is the main class for pagination. It allows you to paginate data by defining the total items, current page, and items per page. It also handles generating the pagination links. - Paginator:
A helper class that handles resolving the current page number from the query string (like?page=2). - Collection:
Laravel’sCollectionclass is often used to wrap arrays. It provides additional helper methods (likepluck(),map(), etc.) to make array manipulation easier, but in this example, we are not using it directly. It’s mostly used for more advanced operations. - Pagination Links:
Thelinks()method outputs the HTML for the pagination controls (previous, next, page numbers, etc.). We’re using the defaultBootstrappagination style here, but you can customize it as needed.
Conclusion
Using illuminate/pagination outside of Laravel is a powerful way to add pagination to your PHP projects without the complexity of bringing in the entire Laravel framework. It allows you to paginate large datasets easily and generate clean, user-friendly navigation links.
By following the steps outlined in this guide, you can set up pagination in just a few lines of code and handle even larger datasets with ease!
