Skip to content

51 model json encodemodel returns and ide loses type after where first#52

Merged
benkhalife merged 2 commits into
mainfrom
51-model-json_encodemodel-returns-and-ide-loses-type-after-where-first
Jun 11, 2026
Merged

51 model json encodemodel returns and ide loses type after where first#52
benkhalife merged 2 commits into
mainfrom
51-model-json_encodemodel-returns-and-ide-loses-type-after-where-first

Conversation

@benkhalife

Copy link
Copy Markdown
Member

No description provided.

Model did not implement JsonSerializable. PHP serializes only public
properties on plain objects, so json_encode($model) produced {}.
toArray() and toJson() were unaffected but any code passing a model
directly to json_encode or inside an array response was silently broken.

Add implements JsonSerializable and jsonSerialize() which delegates
to toArray() — hidden fields, casts, and loaded relations all apply.
Builder::first() is typed as object|false, so User::where(...)->first()
gave the IDE no information about the returned type. Autocompletion and
static analysis were lost after any where() call.

Add ModelBuilder — a thin decorator around Builder that re-declares
terminal methods (first, find, get, paginate, count, etc.) with
model-aware return types. Model::query() and Model::where() now return
ModelBuilder<static> so the IDE knows the result is always the concrete
model class.

All chainable Builder methods (where, orderBy, limit, join, etc.) are
forwarded transparently via __call so existing query chains are
unaffected. Model::with() continues to pass a raw Builder to
EagerBuilder to avoid a type conflict.

Adds regression tests covering:
- json_encode($model) produces correct non-empty output
- hidden fields are excluded from json_encode output
- where()->first() returns model instance, null when no match
- return ['user' => $model] encodes correctly in API responses
Fixed #51
@benkhalife benkhalife merged commit eea0932 into main Jun 11, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Model: json_encode($model) returns {} and IDE loses type after where()->first()

1 participant