📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials CodeIgniter 4 Models in CI4

Models in CI4

6 min read Quiz at the end
Define models with $allowedFields, $useTimestamps, $useSoftDeletes, and validation rules.

Models in CI4

namespace AppModels;
use CodeIgniterModel;

class PostModel extends Model {
    protected $table         = "posts";
    protected $primaryKey    = "id";
    protected $useAutoIncrement = true;
    protected $allowedFields = ["title", "body", "user_id", "slug"];
    protected $useTimestamps = true;
    protected $useSoftDeletes = true;

    // Validation rules
    protected $validationRules = [
        "title" => "required|max_length[255]",
        "body"  => "required",
    ];

    // Return type
    protected $returnType = "AppEntitiesPost";  // or "array"

    // Callbacks
    protected $beforeInsert = ["hashSlug"];
    protected function hashSlug(array $data): array {
        if (isset($data["data"]["title"])) {
            $data["data"]["slug"] = url_title($data["data"]["title"], "-", true);
        }
        return $data;
    }
}

// Usage
$model = model(PostModel::class);
$posts = $model->findAll();
$post  = $model->find(1);
$posts = $model->where("user_id", 1)->orderBy("created_at", "DESC")->findAll();
Topic Quiz · 3 questions

Test your understanding before moving on

1. Which property lists fillable columns in a CI4 model?
💡 $allowedFields lists columns that can be mass-assigned via insert() or update().
2. What does $useTimestamps = true do?
💡 $useTimestamps = true auto-sets created_at and updated_at on save.
3. How do you retrieve all records in a CI4 model?
💡 findAll() returns all rows from the table as an array.