Codeigniter 4 Dynamic Pagination using Pager Tutorial

You know how significant a role pagination plays. Still, you don’t know how to create Pagination to categorize records in Codeigniter.

Don’t worry; this Codeigniter 4 pagination example will show you the righteous methods for building and implementing custom and dynamic Pagination in Codeigniter 4 application.

In this example of Codeigniter 4 pagination, you would learn how to work with the Codeigniter pager library, fetch records from the MySQL database and bind records to Pagination.

The confluence of Codeigniter and pager library will help you create the custom pagination in Codeigniter. Furthermore, the primary mission of this comprehensive Codeigniter dynamic pagination example is to take your skills to the next level.

To create dynamic Pagination, we have to create a model, view, controller, routes, fetch the data into view, and display results with Pagination.

How to Add Pagination in Codeigniter 4 App using Pager Library

  • Step 1: Download Codeigniter App
  • Step 2: Create Table and Add Records
  • Step 3: Insert Database Credentials
  • Step 4: Set Up Model File
  • Step 5: Create Controller File
  • Step 6: Register Route
  • Step 7: Paginate Database Results in View
  • Step 8: Test Pagination Feature

Download Codeigniter App

You need to put the given command to work to install the new Codeigniter app; make sure to configure the Composer tool in advance.

Or else, go ahead and directly download the Codeigniter project from the website.

composer create-project codeigniter4/appstarter

Create Table and Add Records

SQL query is the best option for generating a table, and adding the dummy records into the table. So, let’s add a new table into the database, name it customers or anything you want;

Execute provided command in the SQL console.

--
-- Table structure for `customers` table 
--

CREATE TABLE `customers` (
  `id` int(11) NOT NULL COMMENT 'Primary Key',
  `name` varchar(100) NOT NULL COMMENT 'name',
  `email` varchar(100) NOT NULL COMMENT 'email'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Customers collection';

--
-- Dumping data in `customers` table
--

INSERT INTO `customers` (`id`, `name`, `email`) VALUES
(1, 'Jessica Pierce', 'pierce@hotmail.com'),
(2, 'Tim Spencer', 'spencer@gmail.com'),
(3, 'Charlie Brewer', 'brewer@gmail.com'),
(4, 'Yvonne Washington', 'yvonne@gmail.com'),
(5, 'Marion Matthews', 'marion@gmail.com'),
(6, 'Marshall Palmer', 'palmer@hotmail.com'),
(7, 'Joshua Torres', 'torres@gmail.com'),
(8, 'Mario Powell', 'mario@gmail.com'),
(9, 'James Ferguson', 'james@gmail.com'),
(10, 'Delores Little', 'delores@gmail.com'),
(11, 'Phillip Bennett', 'bennett@hotmail.com'),
(12, 'Lee Washington', 'lee@gmail.com'),
(13, 'Harold Ramirez', 'harold@gmail.com'),
(14, 'Marcia Diaz', 'diaz@gmail.com'),
(15, 'Ramona Castillo', 'ramona@gmail.com');

Insert Database Credentials

You can manage the data only after connecting the application to the database, open the app/Config/Database.php, and insert the database details.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'db_username',
        'password' => 'db_password',
        'database' => 'db_name',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

Set Up Model File

In this section, you will come to know how to create a Model and define table name and table properties in $table and $allowedFields variables.

Open and insert given code in app/Models/CustomerModel.php file.

<?php 
namespace App\Models;
use CodeIgniter\Model;

class CustomerModel extends Model
{

  protected $table = 'customers';

  protected $allowedFields = [
    'name', 
    'email'
  ];

}

Create Controller File

Define index function, use the model to write the query to fetch 5 records simultaneously, similarly bind it to a pager, use view() method to load the view template and pass the customer records into it.

Update app/Controllers/CustomerController.php file.

<?php 
namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\CustomerModel;


class CustomerController extends Controller
{

    public function index() {
        $model = new CustomerModel();
 
        $customers = [
            'customers' => $model->paginate(5),
            'pager' => $model->pager
        ];
        
        return view('index', $customers);
    }
 
}

Register Route

In the previous step, we organized the controller; now we need to form a new route, update the given route in the app/Config/Routes.php.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->get('/customers', 'CustomerController::index');

Paginate Database Results in View

This section will address how to render results from the database and paginate results into the view.

Without further ado, create index.php file and insert the entire given code in app/Views/index.php.

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Codeigniter 4 Pagination Integration Example</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<style>
		.container {
			max-width: 500px;
			margin-top: 50px;
		}
	</style>
</head>

<body>
	<div class="container">
		<table class="table">
			<thead>
				<tr>
					<th>#</th>
					<th>Name</th>
					<th>Email</th>
				</tr>
			</thead>
			<tbody>
				<?php if($customers): ?>
				<?php foreach($customers as $data): ?>
				<tr>
					<td><?php echo $data['id']; ?></td>
					<td><?php echo $data['name']; ?></td>
					<td><?php echo $data['email']; ?></td>
				</tr>
				<?php endforeach; ?>
				<?php endif; ?>
			</tbody>
		</table>

		<!-- pagination blcok -->
		<div class="mt-3">
			<?php if ($pager) :?>
			 <?php $pagi_path='index.php/customers'; ?>
			 <?php $pager->setPath($pagi_path); ?>
			<?= $pager->links() ?>
			<?php endif ?>
		</div>
	</div>
</body>

</html>

Test Pagination Feature

We followed almost every instruction so far and created the desired feature.

Do one more thing and start the app and use url to run the app in the view.

php spark serve
http://localhost:8080/customers

pagination build in Codeigniter

Conclusion

We threw light on the rudiments of the basic SQL query to form pagination, and we feel you will take utter advantage of a pager expressive power.

The pager class is deceptively easy, gives you less pain implementing in Codeigniter. In this tutorial, you learned how to use the pager bit by bit, focused on every nuance to understand the Codeigniter pagination concept.