Skip to content

Codeigniter 8: Using CodeIgniter Models for Efficient REST API Development

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

Codeigniter 8: Using CodeIgniter Models for Efficient REST API Development

Models play a crucial role in CodeIgniter for handling database interactions. They simplify CRUD (Create, Read, Update, Delete) operations and help maintain cleaner, more manageable code in your REST API. This guide will walk you through leveraging CodeIgniter models for efficient REST API development.

 

What Are Models in CodeIgniter?
 

In CodeIgniter, a model is a class that interacts with your database. It acts as a bridge between your application and your database by providing methods for querying, inserting, updating, and deleting data.

 

Step 1: Creating a Model
 

To create a model in CodeIgniter:

  1. Navigate to the app/Models directory.
  2. Create a new file named UserModel.php.
  3. Define the model class:
namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model {
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email'];
    protected $useTimestamps = true; // Automatically manage created_at and updated_at
}

 

Step 2: Using the Model in a Controller
 

CodeIgniter provides two ways to load a model:

  1. Autoloading the Model: Define the model directly in your controller:
    namespace App\Controllers;
    
    use App\Models\UserModel;
    
    class UserController extends BaseController {
        protected $userModel;
    
        public function __construct() {
            $this->userModel = new UserModel();
        }
    
        public function index() {
            $users = $this->userModel->findAll();
            return $this->response->setJSON($users);
        }
    }
  2. Using the model() Method:
    $userModel = model('App\Models\UserModel');
    $users = $userModel->findAll();

 

Step 3: Performing CRUD Operations
 

CodeIgniter models come with built-in methods to perform CRUD operations efficiently.

  1. Create (Insert Data):
    public function createUser() {
        $data = [
            'name' => 'John Doe',
            'email' => 'john@example.com'
        ];
    
        $this->userModel->save($data);
        return $this->response->setJSON(['message' => 'User created successfully']);
    }
  2. Read (Fetch Data):
    • Fetch all records:
      $users = $this->userModel->findAll();
    • Fetch a single record by ID:
      $user = $this->userModel->find($id);
  3. Update Data:
    public function updateUser($id) {
        $data = [
            'name' => 'Updated Name',
            'email' => 'updated@example.com'
        ];
    
        $this->userModel->update($id, $data);
        return $this->response->setJSON(['message' => 'User updated successfully']);
    }
  4. Delete Data:
    public function deleteUser($id) {
        $this->userModel->delete($id);
        return $this->response->setJSON(['message' => 'User deleted successfully']);
    }

 

Step 4: Query Builder Methods
 

For more complex queries, you can use CodeIgniter’s query builder methods within your model:

  1. Filtering Data:
    $users = $this->userModel->where('status', 'active')->findAll();
  2. Joining Tables:
    $builder = $this->db->table('users');
    $builder->join('orders', 'orders.user_id = users.id');
    $results = $builder->get()->getResult();
  3. Custom Queries:
    $query = $this->db->query("SELECT * FROM users WHERE email = 'john@example.com'");
    $result = $query->getRow();

 

Benefits of Using Models
 

  1. Clean Code: Separates database logic from controllers, making the codebase more organized.
  2. Reusability: Reuse model methods across multiple controllers.
  3. Error Handling: Built-in validation and error handling for database operations.
  4. Flexibility: Easily extendable to include custom methods and complex queries.

 

Conclusion
 

By leveraging CodeIgniter models, you can streamline database interactions and create efficient, maintainable REST APIs. Models simplify CRUD operations and allow for clean, structured code that is easy to scale. In the next blog, we’ll explore building a secure REST API in CodeIgniter using JWT authentication.

 

 

 

Recent Posts