CodeIgniter 4 Pagination Tutorial

Introduction

In this tutorial, you will learn how to Use the Pagination Library of CodeIgniter 4. Here, i will be providing instructions and source code for creatiing a simple web application in PHP using CodeIgniter 4 Framework which loads and a multiple data and has a pagination feature. This feature is commonly used in developing a web application for optimizing the page load. This will split your large datasets into pages which helps to improve your application page load.

What is CodeIgniter?

CodeIgniter is an open-source software for web development framework. This can help the web developers that developing a websites or web applications using PHP Langauage. CodeIgniter helps the developer to develop projects much faster.

Getting Started

Before we start, please download and install the following:

Next, extract the codeIgniter 4 zip file in your XAMPP's htdocs directory. Open your terminal or command prompt and change your current directory to your project directory path. Locate the env file in your project root directory and rename it as .env.

Uncomment the CI_ENVIRONMENT by removing the # before the said variable. Change the CI_ENVIRONMENT value into developement so you will see the error if any occurred on your end. Then, configure the your database credential on the same .

(.env) File Example
  1. #--------------------------------------------------------------------
  2. # Example Environment Configuration file
  3. #
  4. # This file can be used as a starting point for your own
  5. # custom .env files, and contains most of the possible settings
  6. # available in a default install.
  7. #
  8. # By default, all of the settings are commented out. If you want
  9. # to override the setting, you must un-comment it by removing the '#'
  10. # at the beginning of the line.
  11. #--------------------------------------------------------------------
  12.  
  13. #--------------------------------------------------------------------
  14. # ENVIRONMENT
  15. #--------------------------------------------------------------------
  16.  
  17. CI_ENVIRONMENT = development
  18.  
  19. #--------------------------------------------------------------------
  20. # APP
  21. #--------------------------------------------------------------------
  22.  
  23. # app.baseURL = ''
  24. # If you have trouble with `.`, you could also use `_`.
  25. # app_baseURL = ''
  26. # app.forceGlobalSecureRequests = false
  27.  
  28. # app.sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler'
  29. # app.sessionCookieName = 'ci_session'
  30. # app.sessionExpiration = 7200
  31. # app.sessionSavePath = null
  32. # app.sessionMatchIP = false
  33. # app.sessionTimeToUpdate = 300
  34. # app.sessionRegenerateDestroy = false
  35.  
  36. # app.CSPEnabled = false
  37.  
  38. #--------------------------------------------------------------------
  39. # DATABASE
  40. #--------------------------------------------------------------------
  41.  
  42. database.default.hostname = localhost
  43. database.default.database = dummy_db
  44. database.default.username = root
  45. database.default.password =
  46. database.default.DBDriver = MySQLi
  47. database.default.DBPrefix =
  48.  
  49. # database.tests.hostname = localhost
  50. # database.tests.database = ci4
  51. # database.tests.username = root
  52. # database.tests.password = root
  53. # database.tests.DBDriver = MySQLi
  54. # database.tests.DBPrefix =
  55.  
  56. #--------------------------------------------------------------------
  57. # CONTENT SECURITY POLICY
  58. #--------------------------------------------------------------------
  59.  
  60. # contentsecuritypolicy.reportOnly = false
  61. # contentsecuritypolicy.defaultSrc = 'none'
  62. # contentsecuritypolicy.scriptSrc = 'self'
  63. # contentsecuritypolicy.styleSrc = 'self'
  64. # contentsecuritypolicy.imageSrc = 'self'
  65. # contentsecuritypolicy.baseURI = null
  66. # contentsecuritypolicy.childSrc = null
  67. # contentsecuritypolicy.connectSrc = 'self'
  68. # contentsecuritypolicy.fontSrc = null
  69. # contentsecuritypolicy.formAction = null
  70. # contentsecuritypolicy.frameAncestors = null
  71. # contentsecuritypolicy.frameSrc = null
  72. # contentsecuritypolicy.mediaSrc = null
  73. # contentsecuritypolicy.objectSrc = null
  74. # contentsecuritypolicy.pluginTypes = null
  75. # contentsecuritypolicy.reportURI = null
  76. # contentsecuritypolicy.sandbox = false
  77. # contentsecuritypolicy.upgradeInsecureRequests = false
  78. # contentsecuritypolicy.styleNonceTag = '{csp-style-nonce}'
  79. # contentsecuritypolicy.scriptNonceTag = '{csp-script-nonce}'
  80. # contentsecuritypolicy.autoNonce = true
  81.  
  82. #--------------------------------------------------------------------
  83. # COOKIE
  84. #--------------------------------------------------------------------
  85.  
  86. # cookie.prefix = ''
  87. # cookie.expires = 0
  88. # cookie.path = '/'
  89. # cookie.domain = ''
  90. # cookie.secure = false
  91. # cookie.httponly = false
  92. # cookie.samesite = 'Lax'
  93. # cookie.raw = false
  94.  
  95. #--------------------------------------------------------------------
  96. # ENCRYPTION
  97. #--------------------------------------------------------------------
  98.  
  99. # encryption.key =
  100. # encryption.driver = OpenSSL
  101. # encryption.blockSize = 16
  102. # encryption.digest = SHA512
  103.  
  104. #--------------------------------------------------------------------
  105. # HONEYPOT
  106. #--------------------------------------------------------------------
  107.  
  108. # honeypot.hidden = 'true'
  109. # honeypot.label = 'Fill This Field'
  110. # honeypot.name = 'honeypot'
  111. # honeypot.template = '<label>{label}</label><input type="text" name="{name}" value=""/>'
  112. # honeypot.container = '<div style="display:none">{template}</div>'
  113.  
  114. #--------------------------------------------------------------------
  115. # SECURITY
  116. #--------------------------------------------------------------------
  117.  
  118. # security.csrfProtection = 'cookie'
  119. # security.tokenRandomize = false
  120. # security.tokenName = 'csrf_token_name'
  121. # security.headerName = 'X-CSRF-TOKEN'
  122. # security.cookieName = 'csrf_cookie_name'
  123. # security.expires = 7200
  124. # security.regenerate = true
  125. # security.redirect = true
  126. # security.samesite = 'Lax'
  127.  
  128. #--------------------------------------------------------------------
  129. # LOGGER
  130. #--------------------------------------------------------------------
  131.  
  132. # logger.threshold = 4
  133.  
  134. #--------------------------------------------------------------------
  135. # CURLRequest
  136. #--------------------------------------------------------------------
  137.  
  138. # curlrequest.shareOptions = true

Creating the Migration

Create a new Migration File in your project by executing php spark make:migration DummyTable in you terminal. Or, you can create a new file named as DummyTable.php inside your app >> Database >> Migrations directory. This file contains the script for creating a "dummy_table" in your database. Then write the following PHP Script.

  1. <?php
  2.  
  3. namespace App\Database\Migrations;
  4.  
  5. use CodeIgniter\Database\Migration;
  6. use CodeIgniter\Database\RawSql;
  7.  
  8. class DummyTable extends Migration
  9. {
  10.     public function up()
  11.     {
  12.         $this->forge->addField([
  13.             'id' => [
  14.                 'type'           => 'INT',
  15.                 'constraint'     => 1,
  16.                 'unsigned'       => true,
  17.                 'auto_increment' => true,
  18.             ],
  19.             'name' => [
  20.                 'type'       => 'VARCHAR',
  21.                 'constraint' => '250',
  22.             ],
  23.             'contact' => [
  24.                 'type' => 'VARCHAR',
  25.                 'constraint' => '100',
  26.             ],
  27.             'email' => [
  28.                 'type' => 'TEXT',
  29.                 'null' => true,
  30.             ],
  31.             'address' => [
  32.                 'type' => 'TEXT',
  33.                 'null' => true,
  34.             ],
  35.             'created_at datetime default current_timestamp',
  36.             'updated_at datetime default current_timestamp on update current_timestamp'
  37.         ]);
  38.         $this->forge->addKey('id', true);
  39.         $this->forge->createTable('dummy_table');
  40.     }
  41.  
  42.     public function down()
  43.     {
  44.         $this->forge->dropTable('dummy_table');
  45.     }
  46. }

Creating the Model

Create a new Model in your project by executing php spark make:model DummyTableModel in you terminal. Or, you can create a new file named as DummyTableModel.php inside your app >> Models directory. This will create your model for your dummy_table in the database. Then Write the following PHP Script.

  1. <?php
  2.  
  3. namespace App\Models;
  4.  
  5. use CodeIgniter\Model;
  6.  
  7. class DummyTableModel extends Model
  8. {
  9.     protected $DBGroup          = 'default';
  10.     protected $table            = 'dummy_table';
  11.     protected $primaryKey       = 'id';
  12.     protected $useAutoIncrement = true;
  13.     protected $insertID         = 0;
  14.     protected $returnType       = 'array';
  15.     protected $useSoftDeletes   = false;
  16.     protected $protectFields    = true;
  17.     protected $allowedFields    = ['name','contact','email', 'address'];
  18.  
  19.     // Dates
  20.     protected $useTimestamps = false;
  21.     protected $dateFormat    = 'datetime';
  22.     protected $createdField  = 'created_at';
  23.     protected $updatedField  = 'updated_at';
  24.     protected $deletedField  = 'deleted_at';
  25.  
  26.     // Validation
  27.     protected $validationRules      = [];
  28.     protected $validationMessages   = [];
  29.     protected $skipValidation       = false;
  30.     protected $cleanValidationRules = true;
  31.  
  32.     // Callbacks
  33.     protected $allowCallbacks = true;
  34.     protected $beforeInsert   = [];
  35.     protected $afterInsert    = [];
  36.     protected $beforeUpdate   = [];
  37.     protected $afterUpdate    = [];
  38.     protected $beforeFind     = [];
  39.     protected $afterFind      = [];
  40.     protected $beforeDelete   = [];
  41.     protected $afterDelete    = [];
  42.  
  43. }

Creating the Seeder

Create a new Seeder File in your project by executing php spark make:seeder DummyTableModelSeeder in you terminal. Or, you can create a new file named as DummyTableModelSeeder.php inside your app >> Database >> Seeds directory. This file contains a PHP script for generating and inserting test data into your dummy_table. Then Write the following PHP Script.

  1. <?php
  2.  
  3. namespace App\Database\Seeds;
  4.  
  5. use CodeIgniter\Database\Seeder;
  6. use App\Models\DummyTableModel;
  7.  
  8. class DummyTableModelSeeder extends Seeder
  9. {
  10.     public function run()
  11.     {
  12.         $dt_model = new DummyTableModel;
  13.         for($i=0; $i < 100; $i++){
  14.             $faker = \Faker\Factory::create();
  15.             $data = [
  16.                 'name'=>$faker->name,
  17.                 'contact'=>$faker->phoneNumber,
  18.                 'email'=>$faker->email,
  19.                 'address'=>$faker->address
  20.             ];
  21.             $dt_model->save($data);
  22.         }
  23.     }
  24. }

Creating the Database and Seed Data

Execute the following command in your terminal:

  • composer install
    • This command will install all the dependencies you need for developing a project using the CodeIgniter Framework.
  • php spark db:create dummy_db
    • This command will create a new database called dummy_db.
  • php spark migrate
    • This command is to migrate your database dummy table.
  • php spark db:seed DummyTableModelSeeder
    • This command will generate and create a dummy data in your db table.

Creating the Page Layout

Create a new folder inside the app >> views naming layouts. Then create a new PHP File naming main.php. This file contains the HTML Script for the main layout or template of your project interface. Write the following code on the file and save it.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     <title>CodeIgniter 4 Pagination</title>
  8.  
  9.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  10.  
  11.  
  12.     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  13.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  14.     <style>
  15.         html, body{
  16.             height:100%;
  17.             width:100%;
  18.         }
  19.     </style>
  20. </head>
  21. <body class="bg-dark bg-gradient bg-opacity-25">
  22.     <nav class="navbar navbar-expand-md navbar-dark bg-primary bg-gradient">
  23.     <div class="container">
  24.         <a class="navbar-brand" href="https://sourcecodester.com">SourceCodester</a>
  25.         <div class="fw-bolder text-light">CI4 Pagination</div>
  26.     </div>
  27.     </nav>
  28.     <div class="container py-4">
  29.         <?= $this->renderSection('content') ?>
  30.     </div>
  31. </body>
  32. <?= $this->renderSection('custom_js') ?>
  33. </html>

Creating the Page Content

Create a new folder inside the app >> views naming pages. Then create a new PHP File naming home.php. This file contains the page content of your page. This file extends the main template. Write the following code on the file and save it.

  1. <?= $this->extend('layouts/main') ?>
  2.  
  3. <?= $this->section('content') ?>
  4. <h1 class="fw-bold">CodeIgniter 4 Pagination</h1>
  5. <hr>
  6. <div class="card rounded-0">
  7.     <div class="card-body">
  8.         <div class="container-fluid">
  9.             <table class="table table-stripped table-bordered">
  10.                 <thead>
  11.                     <tr class="bg-gradient bg-primary text-light">
  12.                         <th class="p-1 text-center">#</th>
  13.                         <th class="p-1 text-center">Name</th>
  14.                         <th class="p-1 text-center">Contact #</th>
  15.                         <th class="p-1 text-center">Email</th>
  16.                         <th class="p-1 text-center">Address</th>
  17.                     </tr>
  18.                 </thead>
  19.                 <tbody>
  20.                     <?php foreach($data as $row): ?>
  21.                         <tr>
  22.                             <td class="px-2 py-1 text-center align-middle"><?= $row['id'] ?></td>
  23.                             <td class="px-2 py-1 align-middle"><?= $row['name'] ?></td>
  24.                             <td class="px-2 py-1 align-middle"><?= $row['contact'] ?></td>
  25.                             <td class="px-2 py-1 align-middle"><?= $row['email'] ?></td>
  26.                             <td class="px-2 py-1 align-middle"><?= $row['address'] ?></td>
  27.                         </tr>
  28.                     <?php endforeach; ?>
  29.                 </tbody>
  30.             </table>
  31.             <?= $pager->makeLinks($page,$perPage, $total, 'custom_view') ?>
  32.            
  33.         </div>
  34.     </div>
  35. </div>
  36. <?= $this->endSection() ?>

Creating the Controller

Create a new Controller by executing the php spark make:controller Main in your terminal. Or, you can create new file naming Main.php inside the app >> Controllers directory. This file contains a PHP script using the CI Controller to render the page and data. Write the following and save the file.

  1. <?php
  2.  
  3. namespace App\Controllers;
  4.  
  5. use App\Models\DummyTableModel;
  6. class Main extends BaseController
  7. {
  8.     public function index()
  9.     {
  10.         $data=[];
  11.         $model = new DummyTableModel;
  12.         $data['page'] = isset($_GET['page']) ? $_GET['page'] : 1;
  13.         $data['perPage'] = 15;
  14.         $data['total'] = $model->countAll();
  15.         $data['data'] = $model->paginate($data['perPage']);
  16.         $data['pager'] = $model->pager;
  17.        
  18.  
  19.         return view('pages/home', $data);
  20.     }
  21. }

Configuring your Default Route

In your app >> Config directory, locate the file named as Routes.php and open it in your preferred text editor. Next, configure yor default controller using the Main Controller. Configure the file like it shown below.

  1. <?php
  2.  
  3. namespace Config;
  4.  
  5. // Create a new instance of our RouteCollection class.
  6. $routes = Services::routes();
  7.  
  8. // Load the system's routing file first, so that the app and ENVIRONMENT
  9. // can override as needed.
  10. if (is_file(SYSTEMPATH . 'Config/Routes.php')) {
  11.     require SYSTEMPATH . 'Config/Routes.php';
  12. }
  13.  
  14. /*
  15.  * --------------------------------------------------------------------
  16.  * Router Setup
  17.  * --------------------------------------------------------------------
  18.  */
  19. $routes->setDefaultNamespace('App\Controllers');
  20. $routes->setDefaultController('Main');
  21. $routes->setDefaultMethod('index');
  22. $routes->setTranslateURIDashes(false);
  23. $routes->set404Override();
  24. // The Auto Routing (Legacy) is very dangerous. It is easy to create vulnerable apps
  25. // where controller filters or CSRF protection are bypassed.
  26. // If you don't want to define all routes, please use the Auto Routing (Improved).
  27. // Set `$autoRoutesImproved` to true in `app/Config/Feature.php` and set the following to true.
  28. //$routes->setAutoRoute(false);
  29.  
  30. /*
  31.  * --------------------------------------------------------------------
  32.  * Route Definitions
  33.  * --------------------------------------------------------------------
  34.  */
  35.  
  36. // We get a performance increase by specifying the default
  37. // route since we don't have to scan directories.
  38. $routes->get('/', 'Main::index');
  39.  
  40. /*
  41.  * --------------------------------------------------------------------
  42.  * Additional Routing
  43.  * --------------------------------------------------------------------
  44.  *
  45.  * There will often be times that you need additional routing and you
  46.  * need it to be able to override any defaults in this file. Environment
  47.  * based routes is one such time. require() additional route files here
  48.  * to make that happen.
  49.  *
  50.  * You will have access to the $routes object within that file without
  51.  * needing to reload it.
  52.  */
  53. if (is_file(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) {
  54.     require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
  55. }

Creating a Custome Template of the Pagination

In the app >> Config directory, open the file named as Pager.php and open it with your text-editor. Then add a new template by adding the new data in the $templates array. Follow the following script.

  1. <?php
  2.  
  3. namespace Config;
  4.  
  5. use CodeIgniter\Config\BaseConfig;
  6.  
  7. class Pager extends BaseConfig
  8. {
  9.     /**
  10.      * --------------------------------------------------------------------------
  11.      * Templates
  12.      * --------------------------------------------------------------------------
  13.      *
  14.      * Pagination links are rendered out using views to configure their
  15.      * appearance. This array contains aliases and the view names to
  16.      * use when rendering the links.
  17.      *
  18.      * Within each view, the Pager object will be available as $pager,
  19.      * and the desired group as $pagerGroup;
  20.      *
  21.      * @var array<string, string>
  22.      */
  23.     public $templates = [
  24.         'default_full'   => 'CodeIgniter\Pager\Views\default_full',
  25.         'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
  26.         'default_head'   => 'CodeIgniter\Pager\Views\default_head',
  27.         'custom_view'   => 'App\Views\layouts\custom_pagination',
  28.     ];
  29.  
  30.     /**
  31.      * --------------------------------------------------------------------------
  32.      * Items Per Page
  33.      * --------------------------------------------------------------------------
  34.      *
  35.      * The default number of results shown in a single page.
  36.      *
  37.      * @var int
  38.      */
  39.     public $perPage = 20;
  40. }

Next, create a new file inside the app >> Views >> layouts naming custom_pagination.php. Then, write the following code and save the file.

  1. <!-- Limit to 3 Links each side of the current page -->
  2. <?php $pager->setSurroundCount(3)  ?>
  3. <!-- END-->
  4.  
  5. <div class="row">
  6.     <!-- Pagination -->
  7.  
  8.     <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
  9.      <ul class="pagination">
  10.             <!-- Previous and First Links if available -->
  11.             <?php if($pager->hasPrevious()): ?>
  12.                 <li class="page-item">
  13.                     <a href="<?= $pager->getFirst() ?>" class="page-link">First</a>
  14.                 </li>
  15.                 <li class="page-item">
  16.                     <a href="<?= $pager->getPrevious() ?>" class="page-link">Previous</a>
  17.                 </li>
  18.             <?php endif; ?>
  19.             <!-- End of Previous and First -->
  20.  
  21.             <!-- Page Links -->
  22.             <?php foreach($pager->links() as $link): ?>
  23.                 <li class="page-item <?= $link['active'] ? 'active' : '' ?>"><a class="page-link" href="<?= $link['uri'] ?>"><?= $link['title'] ?></a></li>
  24.             <?php endforeach; ?>
  25.             <!-- End of Page Links -->
  26.  
  27.             <!-- Next and Last Page -->
  28.             <?php if($pager->hasNext()): ?>
  29.                 <li class="page-item">
  30.                     <a href="<?= $pager->getNext() ?>" class="page-link">Next</a>
  31.                 </li>
  32.                 <li class="page-item">
  33.                     <a href="<?= $pager->getLast() ?>" class="page-link">Last</a>
  34.                 </li>
  35.             <?php endif; ?>
  36.             <!-- End of Next and Last Page -->
  37.         </ul>
  38.     </div>
  39.     <!-- End of Pagination -->
  40.    
  41.     <!-- Pagination Details -->
  42.     <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
  43.         <div class="fw-light fs-italic text-muted text-end">Showing <?= (($page * $perPage) - $perPage +1) ."-". (($page * $perPage) - $perPage + count($data))  ?> Result out of <?= number_format($total) ?></div>
  44.     </div>
  45.     <!-- End of Pagination Details -->
  46. </div>

The code above is the custom template of the pagination of the data.

That's it! You can now test the source code if it runs perfectly as we wanted and see if it meets our goal for this tutorial. To run the simple application, execute php spark serve in your terminal and browse the provided link i.e. http://localhost:8080. Browse the application in your preferred browser such as the Chrome Browser.

DEMO VIDEO

That's the end of this tutorial. I hope this CodeIginter 4 Pagination Tutorial will help you with what you are looking for and you'll find this useful for your current or future PHP Project using the CodeIgniter 4 Framework. You can also download the source code I created for this tutorial. The download button is located below this article.

Explore more on this website for more Tutorials and Free Source Codes.

Enjoy :)

Add new comment