Skip to content

feat: add strict field protection for Models#10302

Open
memleakd wants to merge 2 commits into
codeigniter4:4.8from
memleakd:feat/strict-field-protection
Open

feat: add strict field protection for Models#10302
memleakd wants to merge 2 commits into
codeigniter4:4.8from
memleakd:feat/strict-field-protection

Conversation

@memleakd

Copy link
Copy Markdown
Contributor

Description

This PR proposes adding an opt-in strict field protection mode for Models.

By default, Models keep the existing behavior: fields not listed in $allowedFields are silently discarded before the write reaches the database. With strict field protection enabled, those discarded fields throw a DataException instead:

$model->strictFieldProtection()->insert($data);

This is useful for catching typos, stale form fields, and unexpected write payloads while keeping the existing mass-assignment protection model intact. It does not replace validation and does not inspect the database schema; it only makes the existing $allowedFields discard step explicit when requested.

The implementation keeps the current behavior for operation fields that are needed to locate records, such as the primary key during update() and the index field during updateBatch().

Changes

  • Added $strictFieldProtection and strictFieldProtection() to Models.
  • Added a DataException when strict mode detects fields that would otherwise be discarded.
  • Preserved existing behavior for protect(false), non-auto-increment primary keys, and updateBatch() indexes.
  • Added focused tests for insert, save, update, batch writes, validation order, and default behavior.
  • Updated the user guide, changelog, and model generator template.

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value (without duplication)
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

Add an opt-in Model setting that throws when write data contains fields
that would otherwise be discarded by allowed field protection.

- Add $strictFieldProtection and strictFieldProtection()
- Throw DataException for disallowed write fields in strict mode
- Preserve existing primary key and updateBatch index behavior
- Cover insert, save, update, batch, validation order, and protect(false)
- Document the new option and update the model generator template

Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
@github-actions github-actions Bot added the 4.8 PRs that target the `4.8` branch. label Jun 11, 2026
Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

4.8 PRs that target the `4.8` branch.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant