modess.io - Simple pagination in PHP with the Laravel pagination package









Search Preview

Simple pagination in PHP with the Laravel pagination package | modess.io

modess.io
A simple pagination in PHP can be achieved using the Laravel pagination package. This tutorial features explanations and examples on how to do this.
.io > modess.io

SEO audit: Content analysis

Language Error! No language localisation is found.
Title Simple pagination in PHP with the Laravel pagination package | modess.io
Text / HTML ratio 42 %
Frame Excellent! The website does not use iFrame solutions.
Flash Excellent! The website does not have any flash contents.
Keywords cloud pagination page paginator items = PHP current pages display Laravel presenter currentPage perPage query return results create markup simple
Keywords consistency
Keyword Content Title Description Headings
pagination 32
page 32
paginator 28
items 28
= 27
PHP 25
Headings
H1 H2 H3 H4 H5 H6
2 9 4 0 0 0
Images We found 5 images on this web page.

SEO Keywords (Single)

Keyword Occurrence Density
pagination 32 1.60 %
page 32 1.60 %
paginator 28 1.40 %
items 28 1.40 %
= 27 1.35 %
PHP 25 1.25 %
current 19 0.95 %
pages 17 0.85 %
display 16 0.80 %
14 0.70 %
Laravel 13 0.65 %
presenter 13 0.65 %
currentPage 12 0.60 %
perPage 12 0.60 %
query 12 0.60 %
return 11 0.55 %
results 11 0.55 %
create 9 0.45 %
markup 9 0.45 %
simple 9 0.45 %

SEO Keywords (Two Word)

Keyword Occurrence Density
to display 15 0.75 %
pagination in 14 0.70 %
per page 13 0.65 %
in PHP 13 0.65 %
want to 12 0.60 %
current page 11 0.55 %
the paginator 9 0.45 %
you want 9 0.45 %
in the 9 0.45 %
you need 8 0.40 %
number of 8 0.40 %
you can 7 0.35 %
This is 7 0.35 %
You can 7 0.35 %
the current 7 0.35 %
= new 7 0.35 %
of items 7 0.35 %
of the 7 0.35 %
current items 6 0.30 %
protected function 6 0.30 %

SEO Keywords (Three Word)

Keyword Occurrence Density Possible Spam
pagination in PHP 11 0.55 % No
want to display 9 0.45 % No
you want to 9 0.45 % No
paginator = new 5 0.25 % No
items per page 4 0.20 % No
items to display 4 0.20 % No
number of items 4 0.20 % No
countitems perPage currentPage 4 0.20 % No
you need to 4 0.20 % No
Laravel pagination package 4 0.20 % No
the Laravel pagination 4 0.20 % No
number of pages 3 0.15 % No
creating a pagination 3 0.15 % No
the current page 3 0.15 % No
with Semantic UI 3 0.15 % No
current page from 3 0.15 % No
simple pagination in 3 0.15 % No
to display pages 3 0.15 % No
in your pagination 3 0.15 % No
your own presenter 3 0.15 % No

SEO Keywords (Four Word)

Keyword Occurrence Density Possible Spam
you want to display 6 0.30 % No
the Laravel pagination package 4 0.20 % No
current items to display 3 0.15 % No
the current items to 3 0.15 % No
want to display pages 3 0.15 % No
simple pagination in PHP 3 0.15 % No
a pagination in PHP 3 0.15 % No
isset_GET ? int _GET 2 0.10 % No
Modess and I’m a 2 0.10 % No
Niklas Modess and I’m 2 0.10 % No
is Niklas Modess and 2 0.10 % No
name is Niklas Modess 2 0.10 % No
My name is Niklas 2 0.10 % No
Hi My name is 2 0.10 % No
Simple pagination in PHP 2 0.10 % No
= isset_GET ? int 2 0.10 % No
currentPage = isset_GET ? 2 0.10 % No
string currentPage = isset_GET 2 0.10 % No
query string currentPage = 2 0.10 % No
from query string currentPage 2 0.10 % No

Internal links in - modess.io

continuous integration for Laravel with Jenkins
Laravel & Jenkins: Continuous integration | modess.io
Jenkins & PHP, continuous integration tutorial
Jenkins & PHP, continuous integration tutorial | modess.io
Simple pagination in PHP with the Laravel pagination package
Simple pagination in PHP with the Laravel pagination package | modess.io
PHP micro framework for your REST API – Part 1: Selection
PHP micro framework for your REST API – Part 1: Selection | modess.io
Possible benefits of meditation for developers
Possible benefits of meditation for developers | modess.io
One year of working remote
One year of working remote | modess.io
Older
Blog | modess.io
Talks
Talks | modess.io
Email
Email Protection | Cloudflare

Modess.io Spined HTML


Simple pagination in PHP with the Laravel pagination package | modess.io Jump to: Navigation Simple pagination in PHP with the Laravel pagination package 10 Feb 2016 A simple pagination in PHP can be achieved using the Laravel pagination package. This tutorial features explanations and examples on how to do this.Pagination is something most web developers deal with from time and time. You can create a simple pagination in PHP in many ways. There are a few things to alimony track of when creating a pagination though. Fetching and parsing data, items per page, current page, number of pages, which pages to show and so on. Using a tried and tested package instead of writing your own implementation is often the way to go. Laravel provides the unconfined package illuminate/pagination for pagination that you can use. This package is not depending on the framework in any way.A while when I wrote a blog post on Custom pagination in Laravel 4. That post is now a bit outdated, and it’s moreover somewhat irrelevant if you’re not using Laravel (4). That example creates a new view instead of extending the paginator, something which is a largest practice. Instead you should pericope the paginator from the framework, then you can wield it to any project in need of pagination.How to do simple pagination in PHPPagination is the idea of splitting a hodgepodge of items up into “pages”. Displaying a current set of items while hiding the other ones, linking to those pages. This is for a largest overview and a largest user experience. Pagination in PHP doesn’t differ from pagination in other languages, it’s the same concept. It’s not a ramified task, but you need to have the pursuit in mind when creating a pagination:Items — Your data to display, most often an array.Per page — How many items to exhibit per page. The value will differ for what kind of content you’re displaying. A slide show will have one per page. If you’re displaying links to blog posts, perhaps 10.Total number of pages —Summatethis by dividing the number of items with items per page. Then round that number up to the closest integer. If you have 60 items and want to exhibit 50 per page, the number of pages would be 2. 60 divided by 50 is 1.2, but you want to exhibit full pages so you round that up to 2.Current page — Which page the user is looking at right now. This is for keeping track of getting current items, next/previous links and styling of the current page.Paths — How do you parse the current page from the URL? How do you create links to other pages (paths)? Often using a query string such as /posts?page=3.Total number of items — Only necessary when you want to exhibit page numbers in your pagination. If you only grab 25 items through a database query, you must do a count of the total items you can query also.Database queriesMost often you query a database for paginated results to exhibit in your pagination. Some queries are simple and some are complex, you can wield this concept to any query. The LIMIT modifier consists of two parts, how many results to get and an offset to where it should start. LIMIT 0,10 will start at 0 and fetch the first 10 results. You summate the offset with per page * (current page - 1) as displayed in the image above. The number of results is the value of results per page you want to display.Say you are one page four and want exhibit 20 results, your offset will be 20 * (4 - 1) = 60. The query looks like this:SELECT * FROM your_table LIMIT 60,20; You can have conditionals, joins and so on to your query also. Just wield the limit to it:SELECT yt.* FROM your_table yt JOIN some_table st ON st.join_column = yt.id WHERE yt.category = 'some_category' GROUP BY yt.id LIMIT 60,20; In cases where you want to exhibit pages in your pagination, you need the total value of items. You can do this in two ways. Either you fetch all results from the database, count how many and then use PHP to grab the results you want to display. Or you use the method of limiting the results in your query and execute flipside query for the count.SELECT * FROM your_table LIMIT 60,20; SELECT count(*) FROM your_table;Alimonyin mind the performance implications of both methods. Fetching all results and dealing with them in PHP might be a bad idea for performance if you have a large number of items. I suggest you stick with two database queries in these cases, one for the results and one for the count. For this you should make sure to optimize your queries with indexes.The PHP pagination matriculation in the Laravel pagination packageThe matriculation we’ll use for pagination in PHP is Illuminate\Pagination\Paginator. You can take a squint at the Paginator matriculation in the github repository if you want to swoop deeper. It provides the functionality discussed in the older sections, and it consists of two main parts.The paginator itself implementing the Illuminate\Contracts\Pagination\Paginator interface.A presenter implementing the Illuminate\Contracts\Pagination\Presenter interface.The paginator is responsible for keeping track of the items and managing the pages. The presenter is responsible of generating HTML markup. This is a good separation of responsibility that indulge you to proffer the presentation. By default it uses markup for Bootstrap but you can create presenters for other front-end frameworks, or your own custom markup.PHP pagination exampleStart by installing illuminate/pagination with Composercomposer require illuminate/pagination When you have it installed it you can use it just like any other component. It does not depend on anything in the Laravel framework. Here’s a simple example of pagination with it: <?php require_once __DIR__ . '/vendor/autoload.php'; // Populate items $items = array_map(function ($value) { return [ 'name' => 'Blog post #' . $value, 'url' => '/post/' . $value, ]; }, range(1,1000)); // Get current page from query string $currentPage = isset($_GET['page']) ? (int) $_GET['page'] : 1; // Items per page $perPage = 10; // Get current items calculated with per page and current page $currentItems = array_slice($items, $perPage * ($currentPage - 1), $perPage); // Create paginator $paginator = new Illuminate\Pagination\Paginator($items, 10, $currentPage); ?> <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-xs-12"> <h1>Blog posts - page <?=$paginator->currentPage()?></h1> <?php foreach ($paginator->items() as $blogPost) { ?> <a href="<?=$blogPost['url']?>"><h3><?=$blogPost['name']?></h3></a> <?php } ?> <?=$paginator->render()?> </div> </div> </div> </body> </html> This is all you need to create a pagination in PHP. It populates an variety with “blog posts”, fetches or sets the current page, slices out the current items to exhibit and creates a paginator. Then there is some markup that we moreover render the paginator in. This simple pagination looks like this:When creating the paginator you pass:$items — the current items to display$perPage — items per page$currentPage = null — current page$options = [] — options for path, fragments, etcThe paginator uses Illuminate\Pagination\SimpleBootstrapThreePresenter as its default presenter. As you can see this pagination displays a previous and next link, but no pages. When creating a pagination in PHP, you most often want to exhibit pages.Displaying pagesWould you want to exhibit pages you need flipside presenter, the Illuminate\Pagination\BootstrapThreePresenter. You can’t use this presenter with the default Paginator. Instead you need to create a Illuminate\Pagination\LengthAwarePaginator. This paginator accepts one increasingly parameter when instantiated, the rest is the same.$items — the current items to display.$total — total number of items (this stuff variegated from the previous paginator)$perPage — items per page$currentPage = null — current page$options = [] —options for path, fragments, etc$paginator = new Illuminate\Pagination\LengthAwarePaginator($currentItems, count($items), $perPage, $currentPage); This lawmaking transpiration is all you need to do. It implements the same interface as the simple paginator. Now you have this output instead:If you have hundreds or thousands of pages, you do not want to exhibit them all. By default the paginator deals with this, take note of the truncated pages (…) in the image above. Illuminate\Pagination\UrlWindow that is passed to the presenter handles this responsibility, .Create your own presenterPerhaps you want to create your own presenter for custom markup or flipside CSS framework. This is a simple procedure and I will show this with Semantic UI, like I did in my previous blog post. Extending the paginator with your own presenter is the weightier tideway for your pagination in PHP. The markup for pagination in this CSS framework looks like this:<div class="ui pagination menu"> <a class="active item"> 1 </a> <div class="disabled item"> ... </div> <a class="item"> 10 </a> <a class="item"> 11 </a> <a class="item"> 12 </a> </div> To render this markup you first create a SemanticUIPresenter matriculation and reprinting all contents from Illuminate\Pagination\BootstrapThreePresenter.Alimonythe BootstrapThreeNextPreviousButtonRendererTrait and UrlWindowPresenterTrait since they render buttons for next and previous buttons, and truncating pages. You could create your own implementations of these as well, but they work fine with Semantic UI.Now it’s a matter of updating the markup in the matriculation to match that in the example markup.Moreoveradd some use statements since you aren’t in the Illuminate\Pagination namespace anymore. After that the matriculation will squint like this (I have removed doc blocks to alimony the output lanugo a bit).<?php use Illuminate\Support\HtmlString; use Illuminate\Contracts\Pagination\Paginator as PaginatorContract; use Illuminate\Contracts\Pagination\Presenter as PresenterContract; use Illuminate\Pagination\UrlWindow; use Illuminate\Pagination\BootstrapThreeNextPreviousButtonRendererTrait; use Illuminate\Pagination\UrlWindowPresenterTrait; matriculation SemanticUIPresenter implements PresenterContract { use BootstrapThreeNextPreviousButtonRendererTrait, UrlWindowPresenterTrait; protected $paginator; protected $window; public function __construct(PaginatorContract $paginator, UrlWindow $window = null) { $this->paginator = $paginator; $this->window = is_null($window) ? UrlWindow::make($paginator) : $window->get(); } public function hasPages() { return $this->paginator->hasPages(); } public function render() { if ($this->hasPages()) { return new HtmlString(sprintf( '<div class="ui pagination menu">%s %s %s</div>', $this->getPreviousButton(), $this->getLinks(), $this->getNextButton() )); } return ''; } protected function getAvailablePageWrapper($url, $page, $rel = null) { $rel = is_null($rel) ? '' : ' rel="'.$rel.'"'; return '<a href="'.htmlentities($url).'" class="item"'.$rel.'>'.$page.'</a></li>'; } protected function getDisabledTextWrapper($text) { return '<div class="disabled item">'.$text.'</div>'; } protected function getActivePageWrapper($text) { return '<a class="active item">'.$text.'</a>'; } protected function getDots() { return $this->getDisabledTextWrapper('...'); } protected function currentPage() { return $this->paginator->currentPage(); } protected function lastPage() { return $this->paginator->lastPage(); } } Now you create a new instance of this and pass it to the paginator’s render method.$presenter = new SemanticUIPresenter($paginator); // [...] <?=$paginator->render($presenter)?> This is what the updated view looks like with Semantic UI included and the new presenter:<?php require_once __DIR__ . '/vendor/autoload.php'; // Populate items $items = array_map(function ($value) { return [ 'name' => 'Blog post #' . $value, 'url' => '/post/' . $value, ]; }, range(1,1000)); // Get current page from query string $currentPage = isset($_GET['page']) ? (int) $_GET['page'] : 1; // Items per page $perPage = 10; // Get current items calculated with per page and current page $currentItems = array_slice($items, $perPage * ($currentPage - 1), $perPage); // Create paginator $paginator = new Illuminate\Pagination\LengthAwarePaginator($currentItems, count($items), $perPage, $currentPage); $presenter = new SemanticUIPresenter($paginator); ?> <html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.js"></script> </head> <body> <div class="ui text container"> <h1 class="ui dividing header">Blog posts - page <?=$paginator->currentPage()?></h1> <?php foreach ($paginator->items() as $blogPost) { ?> <a href="<?=$blogPost['url']?>"><h3><?=$blogPost['name']?></h3></a> <?php } ?> <?=$paginator->render($presenter)?> </div> </body> </html> This is what you end up with (ignore the poor padding), a pagination in PHP customized to a CSS framework:Custom URLsYou can transpiration how the paginator constructs URLs for pages. The default is appending ?page=X to the current URL. But you might want /posts/?page=X instead for your paginator. Or you might need to transpiration the query string name. You can either do this when creating the paginator, or by using setters.<?php // Constructor for 'posts/?page=X' $paginator = new Illuminate\Pagination\LengthAwarePaginator( $currentItems, count($items), $perPage, $currentPage, ['path' => 'posts'] ); // Setter for 'posts/?page=X' $paginator->setPath('posts'); // Constructor for '?current_page=X' $paginator = new Illuminate\Pagination\LengthAwarePaginator( $currentItems, count($items), $perPage, $currentPage, ['pageName' => 'current_page'] ); // Setter for ?current_page=X $paginator->setPageName('current_page'); If you want to customise the paginator for pretty URLs, such as posts/page/2. That is not an out of the box-solution and you should take a squint at Laravel Paginator Pretty URLs if this is a solution you need.Why this approach?You might oppose that this isn’t a simple way of dealing with pagination in PHP. I beg to differ. You now have a paginator from one of the most popular PHP frameworks of today. You can manage the version of your dependency and install the one you need. If you write a custom presenter, why not share it with the rest of the world as a Composer package? You could moreover find other presenters that people have written and install them. Less lawmaking in your repository is unchangingly preferable. One less thing to maintain in your application. AboutHi! My name is Niklas Modess and I’m a PHP developer from Stockholm, Sweden. I write mostly on deployment, continuous integration, Laravel and PHP in general. I’m the tragedian of Deploying PHP Applications and organizer of Laravel Stockholm. Social: Twitter GitHub Email Stack Overflow LinkedIn Related Posts Jenkins & PHP, continuous integration tutorial 08 Sep 2016 PHP micro framework for your REST API – Part 1: Selection 07 Jan 2016 Possible benefits of meditation for developers 26 Sep 2015CommentsPlease enable JavaScript to view the comments powered by Disqus.© 2018. All rights reserved. Powered by Hydejack v7.5.0modess.io Hi! My name is Niklas Modess and I’m a PHP developer from Stockholm, Sweden. I write mostly on deployment, continuous integration, Laravel and PHP in general. I’m the tragedian of Deploying PHP Applications and organizer of Laravel Stockholm. Navigation: Talks Social: Twitter GitHub Email Stack Overflow LinkedIn Templates (for web app): Loading… Error Sorry, an error occurred while loading .WhenPermalink