CodeIgniter 4 Pagination Service or Library

Share this Article
Reading Time: 8 minutes
1,329 Views

As we know, in a real time application we store a huge amount of data. They grow as application grows by time. When we design application, we need to take care that how users will browse data at site when we need to show data in bulk.

Now, here Pagination service will comes into play. It allows to break down the results or data sets into small manageable parts.

As you can see here how google manages it’s pagination links when it shows many records on the basis of search keyword.

As we are going to use CodeIgniter 4, so inside this article we will learn How to embed or use CodeIgniter 4 Pagination service?

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.


What is CodeIgniter 4 Pagination Service?

CodeIgniter provides a pre defined library or service which provides a pagination feature. This pagination feature enables or breakdowns the huge data into clickable links which design application and manages in a great way.

In CodeIgniter 4, we can also say it as Pagination service. Now, let’s see how can we load it?

For Pagination we have a service defined in CodeIgniter 4, it will be

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

OR

$pager = service("pager");

Let’s see by making a practical example.


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.

CREATE TABLE tbl_students (
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(120) DEFAULT NULL,
    email varchar(120) DEFAULT NULL,
    mobile varchar(45) DEFAULT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a database and a table. Let’s dump test data into it.

--
-- Dumping data for table `tbl_students`
--

INSERT INTO `tbl_students` (`id`, `name`, `email`, `mobile`) VALUES
(1, 'Sanjay Kumar', 'sanjay@gmail.com', '9632587410'),
(2, 'Vijay Kumar', 'vijay@gmail.com', '7418529630'),
(3, 'Rakesh Kumar', 'rakesh@gmail.com', '8527410963'),
(4, 'Kavita Singh', 'kavita@gmail.com', '8529647130'),
(5, 'Ashish Kumar', 'ashish@gmail.com', '7410852963'),
(6, 'Dhananjay Negi', 'dhananjay_negi@gmail.com', '7896541230'),
(7, 'Pradeep Goyal', 'pradeep_kumar@gmail.com', '1234567890'),
(8, 'Nilu Singh', 'nilu@gmail.com', '7026358941');

Run this query to created database, it will insert these dummy data into tbl_students table.


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
#-------------------------------------------------------------------- 
 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.


Create Route

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

//...

$routes->get("list-student", "Student::listStudent");

Let’s create Model.


Set Application Model

Model is the face of application with the database. We need a Student Model where we will do some basic model configuration.

Models are created at /app/Models. We are going to create StudentModel.php at this location.

$ php spark make:model Student --suffix

It will create StudentModel.php at /app/Models folder. Open file and write this complete code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

class StudentModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'tbl_students';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
		"name",
		"email",
		"mobile"
	];

	// 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          = [];
}

Application Controller Settings

Controller is the functional file.

We will create application controller inside /app/Controllers.

Let’s create Student.php inside the given folder. Open project into terminal and run this.

$ php spark make:controller Student

Open & write the complete code into Student.php file

<?php

namespace App\Controllers;

use App\Models\StudentModel;

class Student extends BaseController
{
    public function listStudent()
    {
        $studentModel = new StudentModel();
      
        return view('list-student', [
            "students" => $studentModel->paginate(3),
            "pager" => $studentModel->pager,
        ]);
    }
}
  • use App\Models\StudentModel; Loading model before use.
  • $studentModel = new StudentModel(); Creating model instance to use.
  • $studentModel->paginate(3) Using pagination service, 3 indicates per page records.
  • $studentModel->pager It creates an instance to call few methods which generated pagination links.

Let’s create view file.


Create View Layout

We need to create view file. View file for List Student.

Create list-student.php inside /app/Views folder. Open file and write this complete code into it.

<table>
  <thead>
    <th>ID</th>
    <th>Name</th>
    <th>Email</th>
  </thead>
  <tbody>
      <?php
        if(count($students) > 0){

            foreach($students as $index => $user){
                ?>
                <tr>
                    <td><?php echo $user['id'] ?></td>
                    <td><?php echo $user['name'] ?></td>
                    <td><?php echo $user['email'] ?></td>
                </tr>
                <?php
            }
        }
      ?>
  </tbody>
</table>

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

Also, we can use $pager->simpleLinks() instead of $pager->links().


Application Testing

Open project into terminal and start development server.

$ php spark serve

URL – http://localhost:8080/list-student

We should get the output as

Added few lines of CSS, it will be like

ul.pagination {
    list-style: none;
    display: flex;
}

li {
    padding: 5px;
}

We hope this article helped you to CodeIgniter 4 Pagination Library in a very detailed way.

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

Leave a Comment