agyanadda@gmail.com

CodeIgniter 4 Models

Database and Models 1 min read Updated Dec 3, 2026 Topic 13 of 30

A model is a class that works with one database table. Extend CodeIgniter\Model and you get ready-made CRUD methods.

Create a model

php spark make:model PostModel, then set its properties:

  • $table = 'posts', $primaryKey = 'id'
  • $allowedFields — columns that can be saved (required; others are ignored, which protects you from unwanted fields)
  • $returnType = 'array' (or 'object', or an Entity class)
  • $useTimestamps = true — fills created_at and updated_at
  • $useSoftDeletes = true — delete() only sets deleted_at

Methods you get

  • findAll(), find($id), first()
  • where('status', 'published')->orderBy('id', 'DESC')->findAll(10)
  • insert($data) — returns the new id
  • update($id, $data), delete($id)
  • save($data) — inserts, or updates if the data has the primary key
  • countAllResults(), paginate(10)

Use it

$model = model(PostModel::class); or new PostModel().

Put custom queries in model methods (like getPublished()), so controllers stay clean.

Example

Example — PostModel with a custom method PHP
<?php
namespace App\Models;

use CodeIgniter\Model;

class PostModel extends Model
{
    protected $table          = 'posts';
    protected $primaryKey     = 'id';
    protected $allowedFields  = ['user_id', 'title', 'slug', 'body', 'status'];
    protected $returnType     = 'array';
    protected $useTimestamps  = true;

    public function getPublished(int $limit = 10): array
    {
        return $this->where('status', 'published')
                    ->orderBy('id', 'DESC')
                    ->findAll($limit);
    }
}

// In a controller
$posts = model(PostModel::class);
$id    = $posts->insert(['user_id' => 1, 'title' => 'Hello CI4', 'slug' => 'hello-ci4', 'body' => '...', 'status' => 'published']);
$post  = $posts->find($id);
echo $post['title'];   // Hello CI4

insert() saves the row (filling created_at and updated_at) and returns its id; find() reads it back as an array.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which property lists the columns a model may save?

Exercise 2 True / False

save() inserts a new row or updates an existing one if the primary key is present.

Exercise 3 Fill in the Blank

Set $use___ = true to fill created_at and updated_at automatically.

Frequently Asked Questions

Those columns are probably missing from $allowedFields. The model silently ignores any field that is not listed there.