How to Create Pagination in Codeigniter 4 Application

 

How to Create Pagination in Codeigniter 4 Application

Step:- 1

first of all i have install codeigniter4 application with Run Command using composer package manager.

composer create-project codeigniter4/appstarter

You can also manually download the Codeigniter application.

Step:- 2

Configure Database Condition

in this step i have configure datbase Include your database name, username and password in application/config/database.php file and make the database connection to handle data dynamically.



    <?php
    public $default = [
            'DSN'      => '',
            'hostname' => 'localhost',
            'username' => 'root',
            'password' => '',
            'database' => 'demo',
            'DBDriver' => 'MySQLi',
            'DBPrefix' => '',
            'pConnect' => false,
            'DBDebug'  => (ENVIRONMENT !== 'production'),
            'charset'  => 'utf8',
            'DBCollat' => 'utf8_general_ci',
            'swapPre'  => '',
            'encrypt'  => false,
            'compress' => false,
            'strictOn' => false,
            'failover' => [],
            'port'     => 3306,
    ];
    ?>



Step:- 3

Create the users table and insert some random data into it, these records will be used through pagination component in Codeigniter application.



   
CREATE TABLE users (
        id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
        name varchar(100) NOT NULL COMMENT 'Name',
        email varchar(255) NOT NULL COMMENT 'Email Address',
        PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
    INSERT INTO `users` (`id`, `name`, `email`) VALUES
    (1, 'Tanveer Ansari', 'tanveeransari@gmail.com'),
    (2, 'Ajay Maurya', 'ajay@gmail.com'),
    (3, 'Salman', 'salman@gmail.com'),
    (4, 'John Doe LI', 'johnli@gmail.com'),
    (5, 'Paul Bettany Ku', 'paulku@gmail.com'),
    (6, 'Vanya Yadav', 'vanyayadav@gmail.com'),



Step:- 4

If anyhow you get the Codeigniter – cannot connect to MySQL database error, then change the hostname value based on your local server e.g MAMPP or XAMPP.



    # MAMPP
    public $default = [
      ...
        'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
      ...
    ]
    # XAMPP
    public $default = [
      ...
        'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
      ...
    ]

Step:- 5

Create Model

Model manifests the particular data and business logic in MVC architecture. It manages the data of the application.

So, we have first create a app/Models/UserModel.php file, thereafter place the following codes.

   
<?php
    namespace App\Models;
    use CodeIgniter\Model;
    class UserModel extends Model
    {
        protected $table = 'users';
        protected $primaryKey = 'id';
        protected $allowedFields = ['name', 'email'];
    }



Step:- 6

Setting Up Controller
Create app/Controllers/UserController.php and insert the following code inside of it.

Import UserModel at the top section of the User controller, create the new UserModel instance. Make the query fetch the records from the database, load the records in the Codeigniter view.


   
<?php
    namespace App\Controllers;
    use App\Models\UserModel;
    use CodeIgniter\Controller;
    class UserController extends Controller
    {
        public function getAll() {
            $userModel = new UserModel();
   
            $data = [
                'users' => $userModel->paginate(6),
                'pager' => $userModel->pager
            ];
           
            return view('user_view', $data);
        }
   
    }



Step:- 7

Define Routes

Create the route, It will be used to display the records in tabular form where we can implement pagination. Place the following code in app/Config/Routes.php.


  $routes->get('users', 'UserController::getAll');



Step:- 8

Display Pagination

Here the compendium of code describes, we have to display the data using Bootstrap 4 Table with Pagination.


Create app/Views/user_view.php file and insert the following code in it.




      <!doctype html>
      <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Codeigniter 4 Pagination Example - codewithtanveer</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
      </head>
      <body>
        <div class="container mt-5">
          <div class="mt-3">
            <table class="table table-bordered" id="users-list">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Name</th>
                  <th>Email</th>
                </tr>
              </thead>
              <tbody>
                <?php if($users): ?>
                <?php foreach($users as $user): ?>
                <tr>
                  <td><?php echo $user['id']; ?></td>
                  <td><?php echo $user['name']; ?></td>
                  <td><?php echo $user['email']; ?></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
            <!-- Pagination -->
            <div class="d-flex justify-content-end">
              <?php if ($pager) :?>
              <?php $pagi_path='index.php/users'; ?>
              <?php $pager->setPath($pagi_path); ?>
              <?= $pager->links() ?>
              <?php endif ?>
            </div>
          </div>
        </div>
      </body>
      </html>





I hope learner this blog is very faithfull for you.

plsase comment 

0 Comments