Skip to content

Codeigniter 5: How to Handle CRUD Operations in a CodeIgniter REST API

Categories :
Computer pc and laptop with programming code on screen

Codeigniter 5: How to Handle CRUD Operations in a CodeIgniter REST API

CRUD operations (Create, Read, Update, Delete) form the foundation of most APIs. In this guide, we’ll explore how to implement these operations in a CodeIgniter REST API using a sample users table.

Step 1: Prepare Your Database
Create a users table in your database:
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Step 2: Set Up a Model
Create a model to interact with the users table:
  1. Navigate to the app/Models directory.
  2. Create a new file named UserModel.php.
  3. Add the following code:
namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model {
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email'];
    protected $useTimestamps = true;
}
Step 3: Create a Controller
Create a controller to handle API requests:
  1. Navigate to the app/Controllers directory.
  2. Create a new file named UserController.php.
  3. Add the following code:
namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\RESTful\ResourceController;

class UserController extends ResourceController {
    protected $modelName = 'App\Models\UserModel';
    protected $format = 'json';

    // Fetch all users
    public function index() {
        $users = $this->model->findAll();
        return $this->respond($users);
    }

    // Fetch a single user by ID
    public function show($id = null) {
        $user = $this->model->find($id);
        if (!$user) {
            return $this->failNotFound('User not found');
        }
        return $this->respond($user);
    }

    // Create a new user
    public function create() {
        $data = $this->request->getPost();
        if (!$this->model->insert($data)) {
            return $this->failValidationErrors($this->model->errors());
        }
        return $this->respondCreated($data, 'User created successfully');
    }

    // Update a user
    public function update($id = null) {
        $data = $this->request->getRawInput();
        if (!$this->model->update($id, $data)) {
            return $this->failNotFound('User not found or data invalid');
        }
        return $this->respondUpdated($data, 'User updated successfully');
    }

    // Delete a user
    public function delete($id = null) {
        if (!$this->model->delete($id)) {
            return $this->failNotFound('User not found');
        }
        return $this->respondDeleted(['id' => $id], 'User deleted successfully');
    }
}
Step 4: Define Routes
Add routes for the CRUD operations in app/Config/Routes.php:
$routes->group('users', function($routes) {
    $routes->get('/', 'UserController::index');
    $routes->get('(:num)', 'UserController::show/$1');
    $routes->post('/', 'UserController::create');
    $routes->put('(:num)', 'UserController::update/$1');
    $routes->delete('(:num)', 'UserController::delete/$1');
});
Step 5: Test Your API
Use a tool like Postman or cURL to test the API:
  1. GET /users: Fetch all users.
  2. GET /users/{id}: Fetch a specific user by ID.
  3. POST /users: Create a new user. Send data like:
    {
        "name": "John Doe",
        "email": "john@example.com"
    }
  4. PUT /users/{id}: Update an existing user. Send data like:
    {
        "name": "John Updated",
        "email": "john_updated@example.com"
    }
  5. DELETE /users/{id}: Delete a user by ID.
Conclusion
Congratulations! You’ve successfully implemented CRUD operations in a CodeIgniter REST API. These foundational operations are the building blocks for more advanced API features. In the next blog, we’ll discuss authentication and authorization to secure your API.

most resent post

Get in Touch

Let’s bring your vision to life. Whether you need a bespoke software solution or a stunning WordPress website, iWorks has the expertise to help you succeed.

Contact Us

98 Nutgrove Avenue, Rathfarnham, Dublin 14, Ireland