Certainly! In CodeIgniter 4, handling different HTTP methods like PUT and PATCH can be done by defining methods within your controller and handling the raw input data. Below is an example of a CodeIgniter 4 controller class that demonstrates how to handle both PUT and PATCH requests for updating user information.
php<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
class UserController extends ResourceController
{
protected $modelName = 'App\Models\UserModel';
protected $format = 'json';
public function update($id = null)
{
if ($this->request->getMethod() === 'put') {
return $this->updatePut($id);
} elseif ($this->request->getMethod() === 'patch') {
return $this->updatePatch($id);
} else {
return $this->failMethodNotAllowed('Only PUT and PATCH methods are allowed');
}
}
private function updatePut($id)
{
// Fetch the raw input data
$input = $this->request->getRawInput();
// Assuming $input contains 'name' and 'email' fields
$data = [
'name' => $input['name'] ?? null,
'email' => $input['email'] ?? null,
];
// Validate the data (you can use CodeIgniter's validation here)
if (empty($data['name']) || empty($data['email'])) {
return $this->failValidationErrors('Name and email are required');
}
// Update the user data in the model
$model = new \App\Models\UserModel();
$model->update($id, $data);
return $this->respond([
'status' => 200,
'message' => 'User updated successfully with PUT method',
]);
}
private function updatePatch($id)
{
// Fetch the raw input data
$input = $this->request->getRawInput();
// Prepare data for partial update
$data = array_filter($input); // Only include non-null values
// Validate the data (optional validation)
if (empty($data)) {
return $this->failValidationErrors('No valid data provided for update');
}
// Update only the specified fields in the model
$model = new \App\Models\UserModel();
$model->update($id, $data);
return $this->respond([
'status' => 200,
'message' => 'User updated successfully with PATCH method',
]);
}
}
update Method:
PUT or PATCH) and calls the appropriate method.updatePut Method:
PUT requests.name and email).updatePatch Method:
PATCH requests.array_filter to exclude null or empty values.Model Interaction:
UserModel is used to interact with the database. Make sure your UserModel extends CodeIgniter\Model and is properly configured to handle user data.UserModel)Here’s a simple example of a UserModel:
php<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email'];
}
By using PUT and PATCH methods appropriately, you ensure that your API adheres to standard practices and is both flexible and efficient.
Congratulations! You've successfully learned about put and patch method differences in codeigniter 4.