What are CodeIgniter 4 models' callbacks?
Answer
CI4 Model callbacks are methods that run automatically before or after database operations — similar to Eloquent model events. Define callback methods in your model and register them: protected $beforeInsert = ["hashPassword", "setCreatedBy"], protected $afterFind = ["formatData"]. Available hooks: beforeInsert, afterInsert, beforeUpdate, afterUpdate, beforeFind, afterFind, beforeDelete, afterDelete. Each callback method receives a $data array containing the operation data and must return the (possibly modified) $data. Example: protected function hashPassword(array $data): array { if (!empty($data["data"]["password"])) { $data["data"]["password"] = password_hash($data["data"]["password"], PASSWORD_BCRYPT); } return $data; }. Callbacks are a clean way to handle cross-cutting concerns like hashing, timestamps, and audit logging.
Previous
What is BaseEntity casting in CodeIgniter 4?
Next
What is the difference between CI4 services and Laravel facades?