agyanadda@gmail.com

CodeIgniter 4 Entities

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

By default models return arrays. An Entity is a class that represents one row as an object, so you can add useful methods and automatic conversions.

Create an entity

php spark make:entity Post creates app/Entities/Post.php extending CodeIgniter\Entity\Entity.

Use it in the model

Set protected $returnType = \App\Entities\Post::class;. Now find() and findAll() return Post objects, and you read columns as properties: $post->title.

Setters and getters

  • A method setTitle($value) runs when you assign $post->title = ... — great for cleaning data or creating a slug
  • A method getTitle() runs when you read $post->title
  • Add your own methods, such as isPublished() or excerpt()

Casts

protected $casts = ['is_featured' => 'boolean', 'options' => 'json-array']; converts values automatically. created_at and updated_at are turned into Time objects by default, so $post->created_at->humanize() gives "2 hours ago".

Saving

Pass the entity to $model->save($post). Only changed fields are updated.

Example

Example — Post entity with a slug setter PHP
<?php
namespace App\Entities;

use CodeIgniter\Entity\Entity;

class Post extends Entity
{
    protected $casts = ['is_featured' => 'boolean'];

    public function setTitle(string $title)
    {
        $this->attributes['title'] = $title;
        $this->attributes['slug']  = url_title($title, '-', true);

        return $this;
    }

    public function excerpt(int $words = 20): string
    {
        helper('text');
        return word_limiter(strip_tags($this->attributes['body'] ?? ''), $words);
    }
}

// Usage (PostModel has $returnType = \App\Entities\Post::class)
$post = new \App\Entities\Post();
$post->title = 'My First Entity Post';
$post->body  = 'Entities make data easy to work with.';
model('PostModel')->save($post);

echo $post->slug;   // my-first-entity-post

Assigning the title also creates the slug "my-first-entity-post". excerpt() can be called in views as $post->excerpt().

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which model property makes find() return entity objects?

Exercise 2 True / False

A setTitle() method runs when you assign $post->title.

Exercise 3 Fill in the Blank

Entities extend CodeIgniter\Entity\___

Frequently Asked Questions

No. Arrays are fine for small projects. Entities help when the same data rules (slugs, formatting, price calculations) appear in many places, because the logic lives in one class.