CodeIgniter 4 Integrate Pagination with Search Filter Tutorial

Reading Time: 7 minutes

In web applications, combining pagination with a search filter enhances user experience by allowing seamless navigation through large datasets while enabling targeted searches. In CodeIgniter 4, integrating pagination with a search filter provides users with an efficient way to browse and find specific information within a dataset.

In this tutorial, we’ll see the comprehensive process of integrating pagination with a search filter in CodeIgniter 4. This functionality empowers developers to create a user-friendly interface where users can navigate through paginated results and refine searches for specific information.

Read More: CodeIgniter 4 Load Data using jQuery Ajax in Select2

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
CI_ENVIRONMENT = development

Now application is in development mode.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.

Create Database Table

Next, we need a table. That table will be responsible to store data.

Let’s create a table with some columns.

  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  name varchar(255) NOT NULL,
  email varchar(255) NOT NULL,
  UNIQUE KEY users_email_unique (email)

Successfully, we have created a table.

Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.


database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306

Now, database successfully connected with the application.

Import Test Data into Table

Here we have some MySQL queries, please execute inside your database. It will insert few dummy rows into users table to go with this article.

-- Dumping data for table `users`

INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'Dorthy Kohler', ''),
(2, 'Dr. Maurice Heller', ''),
(3, 'Miss Skyla Cronin II', ''),
(4, 'Carey Reilly', ''),
(5, 'Mrs. Ressie Gerhold', ''),
(6, 'Albert Hegmann', ''),
(7, 'Prof. Mozelle Tromp DVM', ''),
(8, 'Briana Rippin', ''),
(9, 'Dr. Abigayle Wintheiser', ''),
(10, 'Adolphus Runolfsson', '');

Read More: How To Use Namespace Routes in CodeIgniter 4

Create Model

Open project into terminal run this command.

php spark make:model User

It will create User.php inside /app/Models folder.

Open file and write this code into it.


namespace App\Models;

use CodeIgniter\Model;

class User extends Model
	protected $DBGroup              = 'default';
	protected $table                = 'users';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];

Create Controller

Open project into terminal and run this command to create it.

php spark make:controller Site

It will create Site.php file inside /app/Controllers folder.

Open file and write this complete code into it.


namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\User;

class Site extends BaseController
	public function loadRecord()
		$request = service('request');
		$searchData = $request->getGet(); // OR $this->request->getGet();

		$search = "";
		if (isset($searchData) && isset($searchData['search'])) {
			$search = $searchData['search'];

		// Get data 
		$users = new User();

		if ($search == '') {
			$paginateData = $users->paginate(5);
		} else {
			$paginateData = $users->select('*')
				->orLike('name', $search)
				->orLike('email', $search)    			

		$data = [
			'users' => $paginateData,
			'pager' => $users->pager,
			'search' => $search

		return view('users', $data);

Create Layout File

Create a file with name users.php into /app/Views folder.

Open file and write this code into it.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>CodeIgniter 4 Pagination with Search Filter</title>

    <link rel="stylesheet" type="text/css" href="">
    <style type="text/css">
        a {
            padding-left: 5px;
            padding-right: 5px;
            margin-left: 5px;
            margin-right: 5px;

        .pagination {
            background: deepskyblue;
            color: white;

        .pagination a {
            color: white;
            text-decoration: none;

    <div class='container' style='margin-top: 20px;'>

        <h3 style="text-align: center;margin-bottom: 20px;">CodeIgniter 4 Pagination with Search Filter</h3>
        <!-- Search form -->
        <form method='get' action="loadRecord" id="searchForm">
            <input type='text' name='search' value='<?= $search ?>' placeholder="Search here...">
            <input type='button' id='btnsearch' value='Submit' onclick='document.getElementById("searchForm").submit();'>
        <br />

        <table class="table table-hover" style='border-collapse: collapse;'>
                foreach ($users as $user) {
                    echo "<tr>";
                    echo "<td>" . $user['id'] . "</td>";
                    echo "<td>" . $user['name'] . "</td>";
                    echo "<td>" . $user['email'] . "</td>";
                    echo "</tr>";

        <!-- Paginate -->
        <div style='margin-top: 10px;'>
            <?= $pager->links() ?>



Read More: REST API Development with Validation in CodeIgniter 4

Add Route

Open Routes.php file from /app/Config folder. Add this route into it.


$routes->get('users', 'Site::loadRecord');


Application Testing

Open project terminal and start development server via command:

php spark serve

URL: http://localhost:8080/users

That’s it.

We hope this article helped you to learn about CodeIgniter 4 Integrate Pagination with Search Filter Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more