Skip to content

Codeigniter 12: Handling Pagination and Filtering in CodeIgniter REST APIs

Computer pc and laptop with programming code on screens at software development company.

Codeigniter 12: Handling Pagination and Filtering in CodeIgniter REST APIs

Pagination and filtering are essential for managing large datasets in REST APIs. They improve performance and enhance the user experience by allowing clients to retrieve only the data they need. This guide will demonstrate how to implement pagination and filtering in a CodeIgniter REST API.

 

Why Use Pagination and Filtering?
 

  1. Efficiency: Reduces server load by fetching only the required data.
  2. Scalability: Handles large datasets more effectively.
  3. Improved User Experience: Allows clients to access data in manageable chunks.

 

Step 1: Setting Up Your Database
 

Ensure your database contains a large dataset to test pagination and filtering. For example:

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    category VARCHAR(100),
    price DECIMAL(10, 2),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO products (name, category, price) VALUES
('Product 1', 'Category A', 10.00),
('Product 2', 'Category B', 15.00),
('Product 3', 'Category A', 20.00);

 

Step 2: Implement Pagination in the Controller
 

  1. Fetch Data with Pagination:Use CodeIgniter’s Model to retrieve paginated data:
    namespace App\Controllers;
    
    use App\Models\ProductModel;
    use CodeIgniter\RESTful\ResourceController;
    
    class ProductController extends ResourceController {
        protected $productModel;
    
        public function __construct() {
            $this->productModel = new ProductModel();
        }
    
        public function index() {
            $page = $this->request->getGet('page') ?? 1;
            $perPage = 10;
            
            $data = $this->productModel->paginate($perPage, 'default', $page);
            $pager = $this->productModel->pager;
    
            return $this->respond([
                'data' => $data,
                'pagination' => [
                    'currentPage' => $pager->getCurrentPage(),
                    'totalPages' => $pager->getPageCount(),
                    'perPage' => $perPage,
                    'totalItems' => $pager->getTotal(),
                ]
            ]);
        }
    }
  2. Define the Route:Add a route for the ProductController:
    $routes->get('products', 'ProductController::index');

 

Step 3: Adding Filtering Capabilities
 

  1. Modify the Query for Filtering:Allow filtering based on query parameters (e.g., category, price range):
    public function index() {
        $page = $this->request->getGet('page') ?? 1;
        $perPage = 10;
    
        $category = $this->request->getGet('category');
        $minPrice = $this->request->getGet('min_price');
        $maxPrice = $this->request->getGet('max_price');
    
        $query = $this->productModel;
    
        if ($category) {
            $query = $query->where('category', $category);
        }
    
        if ($minPrice && $maxPrice) {
            $query = $query->where('price >=', $minPrice)->where('price <=', $maxPrice);
        }
    
        $data = $query->paginate($perPage, 'default', $page);
        $pager = $this->productModel->pager;
    
        return $this->respond([
            'data' => $data,
            'pagination' => [
                'currentPage' => $pager->getCurrentPage(),
                'totalPages' => $pager->getPageCount(),
                'perPage' => $perPage,
                'totalItems' => $pager->getTotal(),
            ]
        ]);
    }
  2. Test Filtering: Use query parameters to filter results:
    • Example 1: /products?category=Category+A
    • Example 2: /products?min_price=10&max_price=20

 

Step 4: Testing Pagination and Filtering
 

Use tools like Postman or a web browser to test the API:

  1. Paginated Results:
    • URL: /products?page=2
    • Response:
      {
          "data": [...],
          "pagination": {
              "currentPage": 2,
              "totalPages": 5,
              "perPage": 10,
              "totalItems": 50
          }
      }
  2. Filtered Results:
    • URL: /products?category=Category+A&min_price=10&max_price=20
    • Response:
      {
          "data": [...],
          "pagination": {
              "currentPage": 1,
              "totalPages": 1,
              "perPage": 10,
              "totalItems": 3
          }
      }

 

Best Practices for Pagination and Filtering
 

  1. Default Values: Always provide default values for pagination parameters to avoid errors.
  2. Validation: Validate query parameters to ensure they are within acceptable ranges.
  3. Performance: Optimize database queries with proper indexing for frequently filtered columns.
  4. Documentation: Clearly document available query parameters and their usage for API consumers.

 

Conclusion
  

Pagination and filtering are vital for managing large datasets effectively in REST APIs. By following the steps in this guide, you can implement these features in CodeIgniter to enhance performance and usability. In the next blog, we’ll explore building a REST API for user management with CodeIgniter.
 

 

 

Recent Posts