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.
CREATE TABLE users (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY users_email_unique (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
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 #-------------------------------------------------------------------- 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', 'bosco.jessie@example.net'), (2, 'Dr. Maurice Heller', 'kanderson@example.org'), (3, 'Miss Skyla Cronin II', 'donavon61@example.com'), (4, 'Carey Reilly', 'will.marlee@example.org'), (5, 'Mrs. Ressie Gerhold', 'dedric.hodkiewicz@example.com'), (6, 'Albert Hegmann', 'stark.delphine@example.com'), (7, 'Prof. Mozelle Tromp DVM', 'trantow.nathaniel@example.org'), (8, 'Briana Rippin', 'buddy22@example.com'), (9, 'Dr. Abigayle Wintheiser', 'adriana.muller@example.net'), (10, 'Adolphus Runolfsson', 'emiliano.nitzsche@example.net');
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.
<?php 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.
<?php 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) ->paginate(5); } $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> <html> <head> <meta charset="utf-8"> <title>CodeIgniter 4 Pagination with Search Filter</title> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css"> <style type="text/css"> a { padding-left: 5px; padding-right: 5px; margin-left: 5px; margin-right: 5px; } .pagination li.active { background: deepskyblue; color: white; } .pagination li.active a { color: white; text-decoration: none; } </style> </head> <body> <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();'> </form> <br /> <table class="table table-hover" style='border-collapse: collapse;'> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> <?php foreach ($users as $user) { echo "<tr>"; echo "<td>" . $user['id'] . "</td>"; echo "<td>" . $user['name'] . "</td>"; echo "<td>" . $user['email'] . "</td>"; echo "</tr>"; } ?> </tbody> </table> <!-- Paginate --> <div style='margin-top: 10px;'> <?= $pager->links() ?> </div> </div> </body> </html>
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.