CodeIgniter 4 Pagination with Search Filter Tutorial

Share this Article
Reading Time: 7 minutes

Inside this article we will see the concept of CodeIgniter 4 pagination with search filter. We will use the concept of pagination service.

We will create a table with pagination links and a search filter into it. This tutorial will be easy to understand and step by step guide. Already we have an article about Pagination service in CodeIgnitere 4, Click here to learn.

Also we have option to use jQuery DataTable plugin to create table with all these features, but we will create server side datatable in CodeIgniter 4.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.

Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system.

To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Turn Development Mode On

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

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.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

 // Do it to 
CI_ENVIRONMENT = development

Now application is in development mode.

Create Database, Table & Test Data in Application

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

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create 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)

Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi

Now, database successfully connected with 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', '');

Create Model

Open project into terminal run this command.

$ php spark make:model User

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

open User.php 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 Site.php 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();

		$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 users.php 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() ?>



Add Route

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


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


Application Testing

Start development server:

$ php spark serve

URL – http://localhost:8080/users

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

Buy Me a Coffee

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.

Find More on CodeIgniter 4 here