CodeIgniter 4 - Pagination

Posted by Ridwan Fadilah on Sep 26, 2020 - 08:01 pm

Pagination

CodeIgniter 4 Tutorial. How to add pagination in PHP CodeIgniter 4 Framework

Adding pagination in CodeIgniter 4 is very simple. CodeIgniter 4 has a flexible pagination library to the theme on your page. In CodeIgniter 4, the pagination works with the model.

The pagination is capable of supporting multiple paginators on a single page.

Table of Contents

Preparation

Before we start to add pagination, be sure you have a page and a database table with much data to see the result of the pagination works.

Table Data

In this article, the data has made with a faker. You can see the tutorial about CodeIgniter 4 - Seeder and Faker to generated dummy data.

Just make a simple page view with also a simple controller and model.

Here's the folder structure:

Folder Structure
Controller

The first is to make a controller. Just make a simple controller like:


<?php

namespace App\Controllers;

use App\Models\PeoplesModel;

class Peoples extends BaseController
{
  public function index()
  {
    $peoples = new peoplesModel();

    $data['pageTitle'] = 'CI-4 | Peoples';

    // load view
    return view('peoples/index', $data);
  }
}
Model

Like the controller above, the model in this example is also simple:


<?php

namespace App\Models;

use CodeIgniter\Model;

class PeoplesModel extends Model
{
  // your table
  protected $table = 'peoples';
  // primary key
  protected $primaryKey = 'id';
  // table fields
  protected $allowedFields = ['name', 'address', 'created_at', 'updated_at'];
}

Now, you can make a page view to paginating the database result.

Loading The Pagination Library

Like all services in CodeIgniter 4, it can be loaded via Config\Services, though you usually will not need to load it manually:


$pager = \Config\Services::pager();

Paginating Database Results

There are methods of so-called "paginate" and "pager."

In CodeIgniter 4, to paginating database results, you only need to invoke these methods inside the model.

You need to add a parameter to the paginate method. A parameter in this method is the number of the database results you want to show on a single page, while the pager is a method to display the pagination links.

The paginate and pager method is the same as the "findAll" method. These are the built-in method available and embedded in CodeIgniter 4 model.

To provide a paginated list of peoples in your application, your controller’s method would look something like:


public function index()
  {
    $peoples = new peoplesModel();

    $data['pageTitle'] = 'CI-4 | Peoples';

    // load database results with pagination
    $data['table'] = $peoples->paginate(6);
    // load the pagination links
    $data['pager'] = $peoples->pager;

    // load view
    return view('peoples/index', $data);
  }

Now, to display the pagination links, just add this line to your page view:


<?= $pager->links(); ?>

Or, you can also use this code:


<?= $pager->simpleLinks(); ?>

Example:


<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Name</th>
      <th scope="col">Address</th>
      <th scope="col">Created At</th>
      <th scope="col">Updated At</th>
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    <!-- your database result-->
    .............
  </tbody>
</table>

<?= $pager->links(); ?>

The result of the example above will display by the browser like this:

CodeIgniter 4 Pagination Example

Customizing The Pagination Links

You can customize the links by editing this file app/Config/Pager.php:


public $templates = [
    'default_full'   => 'CodeIgniter\Pager\Views\default_full',
    'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
    'default_head'   => 'CodeIgniter\Pager\Views\default_head',
];

In this article, we'll not edit the Pager.php file. We'll try to make a new template with Bootstrap.

See the tutorial about How to Ingrating Bootstrap in CodeIgniter 4.

First, add a new template namespace (directory) to the app/Config/Pager.php file:


public $templates = [
    'default_full'   => 'CodeIgniter\Pager\Views\default_full',
    'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
    'default_head'   => 'CodeIgniter\Pager\Views\default_head',
    'peoples_pagination' => 'App\Views\Pagers\peoples_pagination'
];

Now, create a new file and folder:

CodeIgniter 4 Pagination Templates Folder

Add the Bootstrap pagination code:

Bootstrap Pagination Code

Once you have created and configured the template, you need to invoke (call) it on your page. Just add the parameters to the $pager->links():


<?= $pager->links('peoples', 'peoples_pagination'); ?>

The first parameter is the name of the table, the second parameter is the pager template.

The example above will display by the browser like this:

Custom Pagination Links
Important to note: You didn't have the logic on the links template. The pagination will not work yet.

Creating The View

To make the custom pagination work, you need to add another configuration on your controller.

Add a new parameter to the paginate method:


// for row number order
$data['currentPage'] = $this->request->getVar('page_peoples') ? $this->request->getVar('page_peoples') : 1;
// load table
$data['table'] = $peoples->paginate(6, 'peoples');

The second parameter is the table name.

Now, you need to "re-customizing" your pagination template.

Example:


<?php $pager->setSurroundCount(2) ?>

<nav aria-label="Page navigation">
  <ul class="pagination">
    <?php if ($pager->hasPrevious()) : ?>
      <li class="page-item">
        <a class="page-link" href="<?= $pager->getFirst() ?>" aria-label="<?= lang('Pager.first') ?>">
          <span aria-hidden="true"><?= lang('Pager.first') ?></span>
        </a>
      </li>
      <li class="page-item">
        <a class="page-link" href="<?= $pager->getPrevious() ?>" aria-label="<?= lang('Pager.previous') ?>">
          <span aria-hidden="true"><?= lang('Pager.previous') ?></span>
        </a>
      </li>
    <?php endif ?>

    <?php foreach ($pager->links() as $link) : ?>
      <li class="page-item <?= $link['active'] ? 'active' : '' ?>">
        <a class="page-link" href="<?= $link['uri'] ?>">
          <?= $link['title'] ?>
        </a>
      </li>
    <?php endforeach ?>

    <?php if ($pager->hasNext()) : ?>
      <li class="page-item">
        <a class="page-link" href="<?= $pager->getNext() ?>" aria-label="<?= lang('Pager.next') ?>">
          <span aria-hidden="true"><?= lang('Pager.next') ?></span>
        </a>
      </li>
      <li class="page-link" class="page-item">
        <a href="<?= $pager->getLast() ?>" aria-label="<?= lang('Pager.last') ?>">
          <span aria-hidden="true"><?= lang('Pager.last') ?></span>
        </a>
      </li>
    <?php endif ?>
  </ul>
</nav>
In the first line, the setSurroundCount() method specifies than we want to show two links to either side of the current page link. The only parameter that it accepts is the number of links to show. - codeigniter.github.io

In this example, the table row number on the page view is also re-configured:


<table>
  <thead>
    ......
  </thead>
  <tbody>
    <!-- the '6' is must the same as the paginate method parameter -->
    <?php $i = 1 + (6 * ($currentPage - 1)); ?>
    <?php foreach ($table as $t) : ?>
      <tr>
        .....
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

Now, the custom pagination will display and work like this:

CodeIgniter 4 Custom Pagination Link

Okay, that's the CodeIgniter 4 tutorial about how add pagination. You can find another tutorial on our YouTube Channel. You can also find the full source code of these examples on our GitHub.

Thanks for reading!


Related Articles