CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New

How to Create Pagination in Codeigniter 4


Go to app/Models/ and create here one model.

Model

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

Now Go to app/Controllers and create a controller name

Controller

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

View

<!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 - Tutsmake.com</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
 
   <div class="container">
    <div class="row mt-5">
       <table class="table table-bordered">
         <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>
        <div class="row">
          <div class="col-md-12">
            <div class="row">
              <?php if ($pager) :?>
              <?php $pagi_path='demo/public/index.php/users'; ?>
              <?php $pager->setPath($pagi_path); ?>
              <?= $pager->links() ?>
              <?php endif ?>        
             </div> 
          </div>
        </div>
    </div>
  </div>
</div> 
</body>
</html>