After this lesson you can define a model for the books table and explain what its allowed-field list does and does not protect. A model is a convenient data boundary. It gives controllers a named way to find, insert, update and delete records without repeating table configuration everywhere.
Define the model contract
Create app/Models/BookModel.php with this complete class. The books table must already exist through the migration, and the default connection must still point at the disposable SQLite database.
<?php
namespace App\Models;
use CodeIgniter\Model;
class BookModel extends Model
{
protected $table = 'books';
protected $primaryKey = 'id';
protected $returnType = 'array';
protected $allowedFields = ['title'];
}This model was linted and used by both the HTML catalogue and JSON API during verification. The table property names storage. The primary key identifies rows. The return type makes retrieved records arrays, matching the templates' bracket syntax. Keeping these choices explicit helps a beginner understand what the controller receives.
The official Using CodeIgniter's Model guide documents these properties and model methods. A model does not automatically create its table. If a query fails with a missing-table error, revisit connection and migration state instead of renaming the class until something changes.
Understand the allowed-field boundary
Allowed fields restrict which data keys the model accepts for insert and update operations. Here title is the only writable field. The identifier is database-managed and is not in that list. This helps protect against accidentally passing unexpected input fields into persistence.
It is not authorization. A caller who reaches an unprotected action can still change an allowed title. It is not a substitute for validating the title's type, presence or length. It also does not retroactively protect direct query-builder operations that bypass the model's field filtering. Think of it as one specific boundary, not a general security label.
In the course controller we construct an explicit title array before calling insert or update. That makes the intended input visible even though the model also has an allowlist. Multiple narrow boundaries can complement each other when their purposes are clear.
Read through the model
This method fragment will become the catalogue action in the next page-building lesson. Place it inside Books and import App\Models\BookModel at the top of the file when you use it.
public function index(): string
{
return view('books/index', [
'books' => (new \App\Models\BookModel())->orderBy('id')->findAll(),
]);
}The fragment was syntax-checked and its equivalent action served the verified catalogue. The explicit order makes the demonstration predictable. Without an ordering requirement, applications should not depend on a coincidental row order. The view file does not exist until the catalogue-pages lesson, so complete that stage before requesting this action.
The find method retrieves by the configured primary key. A missing single record can return null; the controller must handle that before passing data into a detail template. A list query can return an empty array, which is a valid catalogue state rather than necessarily a database error.
Avoid hiding policy in convenient methods
A model can support validation, callbacks and other facilities, but this course begins with a small configuration-only model. We validate at the request boundary so that beginners can follow the rejection path. If you later move shared rules into a model, keep tests that prove every input path applies the intended policy.
Do not assume a generic save method can decide all create-versus-update semantics for your application. A malicious or mistaken identifier can change the operation you intended. The bookshop's create action omits the identifier; its update action receives the identifier from an explicit route and checks existence first.
Share data behavior, not presentation
Both a browser page and an API can use BookModel. They should not share a rendered HTML fragment as their data source. The browser view escapes title text into markup; the API serializes the original title into JSON. Keeping presentation outside the model lets those responses differ appropriately.
The fetched official Model guide supports the model API used here. Our allowlist and array return shape were exercised against actual seeded records. No feature in this lesson establishes a user account, a permission check or a production-ready catalogue administrator.
Common mistakes
Treating allowedFields as a login system leaves permitted columns writable by anyone who reaches the action. Expecting the model to create its table skips migrations. Mixing array and object access causes template errors. Finally, using a direct builder write while assuming model callbacks and allowlists still apply bypasses the boundary you thought you were using.
Exercise
A submitted request contains title and is_admin. Which key is allowed by this model, and does that prove the caller may add a book? Then explain why the HTML and JSON endpoints can share BookModel but should render its results differently.
Show an answer
Only title is on the write allowlist. That restricts fields, not caller permissions, so authorization is still required before public writes. Both endpoints can retrieve the same original records; the HTML view escapes them for its output context while the API uses JSON response serialization.
Previous lesson · Next lesson · Related: explicit routes · Related: security boundaries
Key points
- BookModel maps the books table to array records.
- Allowed fields limit persistence keys, not user permissions.
- HTML and JSON can share data access while using different output handling.