CodeIgniter already has a pagination library using which you can easily add pagination on your page.
In this tutorial, I show how you can create pagination with a search filter in the CodeIgniter 4 project.
Contents
1. Database configuration
- Open
.env
file which is available at the project root.
NOTE – If dot (.) not added at the start then rename the file to .env.
- Remove # from start of database.default.hostname, database.default.database, database.default.username, database.default.password, and database.default.DBDriver.
- Update the configuration and save it.
database.default.hostname = 127.0.0.1 database.default.database = testdb database.default.username = root database.default.password = database.default.DBDriver = MySQLi
2. Create Table
- Create a new table
users
using migration.
php spark migrate:create create_users_table
- Now, navigate to
app/Database/Migrations/
folder from the project root. - Find a PHP file that ends with
create_users_table
and open it. - Define the table structure in the
up()
method. - Using the
down()
method deleteusers
table which calls when undoing migration.
<?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; class CreateUsersTable extends Migration { public function up() { $this->forge->addField([ 'id' => [ 'type' => 'INT', 'constraint' => 5, 'unsigned' => true, 'auto_increment' => true, ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '100', ], 'email' => [ 'type' => 'VARCHAR', 'constraint' => '100', ], 'city' => [ 'type' => 'VARCHAR', 'constraint' => '100', ], ]); $this->forge->addKey('id', true); $this->forge->createTable('users'); } //-------------------------------------------------------------------- public function down() { $this->forge->dropTable('users'); } }
- Run the migration –
php spark migrate
3. Model
- Create
Users.php
file inapp/Models/
folder. - Open the file.
- Specify table name
"users"
in$table
variable, primary key"id"
in$primaryKey
, Return type"array"
in$returnType
. - In
$allowedFields
Array specify field names –['name', 'email','city']
that can be set during insert and update.
Completed Code
<?php namespace App\Models; use CodeIgniter\Model; class Users extends Model { protected $table = 'users'; protected $primaryKey = 'id'; protected $returnType = 'array'; protected $allowedFields = ['name', 'email','city']; protected $useTimestamps = false; protected $validationRules = []; protected $validationMessages = []; protected $skipValidation = false; }
4. Route
- Open
app/Config/Routes.php
file. - Define 2 routes –
- /
- loadRecord – Create pagination.
Completed Code
$routes->get('/', 'UsersController::index'); $routes->get('loadRecord', 'UsersController::loadRecord');
5. Controller
Create UsersController.php
file in app/Controllers/
folder.
Create 2 methods –
- index() – Redirect to
'loadRecord'
route. - loadRecord() – Using this method create pagination.
Read search value and assign to $search
variable. Create object of Users
Model.
Call paginate()
method on the $users
object and pass a number (how many rows display per page).
If $search
is not empty then search $search
in name, email, and city fields using like()
.
Initialize $data
Array with –
$data = [ 'users' => $paginateData, 'pager' => $users->pager, 'search' => $search ];
Pass fetched data to 'users'
key, $users->pager
to 'pager'
, and $search
to 'search'
key.
Using 'users'
key access fetched data in view and with 'pager'
key create pagination links.
Load index
view and pass $data
.
Completed Code
<?php namespace App\Controllers; use App\Models\Users; class UsersController extends BaseController{ public function index(){ return redirect()->route('loadRecord'); } public function loadRecord(){ $request = service('request'); $searchData = $request->getGet(); $search = ""; if(isset($searchData) && isset($searchData['search'])){ $search = $searchData['search']; } // Get data $users = new Users(); if($search == ''){ $paginateData = $users->paginate(5); }else{ $paginateData = $users->select('*') ->orLike('name', $search) ->orLike('email', $search) ->orLike('city', $search) ->paginate(5); } $data = [ 'users' => $paginateData, 'pager' => $users->pager, 'search' => $search ]; return view('index',$data); } }
6. View
Create index.php
file in app/Views
.
Create <form method='get' action="loadRecord" id="searchForm">
and add a textbox and a button. Add onclick
event on button to submit the <form >
.
Loop on the $users
to list fetched records.
Display pagination link using $pager->links()
.
Completed Code
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Make Pagination with search filter in CodeIgniter 4</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;'> <!-- Search form --> <form method='get' action="loadRecord" id="searchForm"> <input type='text' name='search' value='<?= $search ?>'><input type='button' id='btnsearch' value='Submit' onclick='document.getElementById("searchForm").submit();'> </form> <br/> <table class="table table-hover" border='1' style='border-collapse: collapse;'> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>City</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 "<td>".$user['city']."</td>"; echo "</tr>"; } ?> </tbody> </table> <!-- Paginate --> <div style='margin-top: 10px;'> <?= $pager->links() ?> </div> </div> </body> </html>
7. Run
- Navigate to the project using Command Prompt if you are on Windows or terminal if you are on Mac or Linux, and
- Execute “php spark serve” command.
php spark serve
- Run
http://localhost:8080
in the web browser.
8. Demo
9. Conclusion
You can learn more about the pagination library from here.
If you want more flexibility and features with pagination then you can use datatable plugin. You can view this tutorial to know datatable pagination integration in CodeIgniter 4.
If you found this tutorial helpful then don't forget to share.