Pagination
This example demonstrates how to use the Pagination class to paginate database results in a LavaLust application.
Folder Structure
app/
├── controllers/
│ └── BlogController.php
│
├── models/
│ └── BlogModel.php
│
└── views/
└── blog/
└── index.php
Database Table Structure
Table: blog_posts
Column |
Type |
Description |
|---|---|---|
id |
INT PK AI |
Post ID |
title |
VARCHAR(255) |
Post title |
content |
TEXT |
Post content |
created_at |
DATETIME |
Created date |
Controller
<?php
class BlogController extends Controller
{
public function index()
{
$this->call->library('pagination');
$current_page = (int) segment(2) ?: 1;
$total_rows = $this->BlogModel->count();
$rows_per_page = 5;
$base_url = 'blog/index';
$page_data = $this->pagination->initialize(
$total_rows,
$rows_per_page,
$current_page,
$base_url,
5
);
$this->pagination->set_theme('tailwind');
// Calculate offset yourself (cleanest)
$offset = ($current_page - 1) * $rows_per_page;
// Correct usage with the new limit() method
$blogs = $this->BlogModel
->query()
->limit($rows_per_page, $offset) // limit, offset
->get_all(); // or ->result() / ->result_array()
$this->call->view('blog/index', [
'blogs' => $blogs,
'pagination' => $this->pagination->paginate(),
]);
}
}
?>
View
<?php foreach($blogs as $post): ?>
<h2><?= $post['title'] ?></h2>
<p><?= $post['content'] ?></p>
<?php endforeach; ?>
<div class="pagination">
<?= $pagination ?>
</div>