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:
Navigate to the
app/Models
directory.Create a new file named
UserModel.php
.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:
Navigate to the
app/Controllers
directory.Create a new file named
UserController.php
.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:
GET
/users
: Fetch all users.GET
/users/{id}
: Fetch a specific user by ID.POST
/users
: Create a new user. Send data like:{ "name": "John Doe", "email": "john@example.com" }
PUT
/users/{id}
: Update an existing user. Send data like:{ "name": "John Updated", "email": "john_updated@example.com" }
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.