Inside this article we will see the concept i.e CodeIgniter 4 How To Work with Pagination Library Tutorial. Article contains the classified information about How to Create Pagination in Codeigniter 4 Application.
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.
Learn More –
Complete CodeIgniter 4 Routing Tutorial in Details- Complete CodeIgniter 4 Spark CLI Tutorial
- Complete Concept of Named Route in CodeIgniter 4 Tutorial
- Concept of Date And Time in CodeIgniter 4 Tutorial
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.
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
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 & Test Data
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 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 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 #-------------------------------------------------------------------- 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.
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 terminal and start development server via command:
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 learn about CodeIgniter 4 How To Work with Pagination Library 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.