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— fillscreated_atandupdated_at$useSoftDeletes = true—delete()only setsdeleted_at
Methods you get
findAll(),find($id),first()where('status', 'published')->orderBy('id', 'DESC')->findAll(10)insert($data)— returns the new idupdate($id, $data),delete($id)save($data)— inserts, or updates if the data has the primary keycountAllResults(),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.