@tolki/ts 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +572 -68
- package/dist/enums.d.ts +1 -1
- package/dist/routes.d.ts +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -833,6 +833,166 @@ export interface Product {
|
|
|
833
833
|
|
|
834
834
|
`#[TsType]` also accepts a plain string (`#[TsType('{width: number, height: number}')]`) when the type doesn't need an import.
|
|
835
835
|
|
|
836
|
+
### Laravel 13 Model Attributes
|
|
837
|
+
|
|
838
|
+
Laravel 13 shipped a set of native class attributes across Eloquent models (`Illuminate\Database\Eloquent\Attributes`) and API resources (`Illuminate\Http\Resources\Attributes`) that replace older property-based conventions (`#[Table]` instead of `protected $table`, and so on). These are **not** attributes from this package — no `use AbeTwoThree\LaravelTsPublish\Attributes\...` needed — and most of them are honored automatically, with no configuration and no code change on your end, because Laravel resolves them into the model's ordinary instance state before this package ever reads the model:
|
|
839
|
+
|
|
840
|
+
| Attribute | Honored? | Notes |
|
|
841
|
+
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
842
|
+
| `#[Table('...')]` | Yes | Changes which table columns are read from, same as `protected $table`. |
|
|
843
|
+
| `#[Hidden(['col'])]` | Yes | Feeds the same `hidden` flag `protected $hidden` does — see [What gets published: hidden attributes](#what-gets-published-hidden-attributes-write-only-accessors). |
|
|
844
|
+
| `#[Visible(['col'])]` | Yes | An **allowlist** — every column _not_ listed becomes hidden, same as `protected $visible`. List every column meant to stay published, or most of the model will disappear from the generated interface. |
|
|
845
|
+
| `#[Appends(['accessor'])]` | Yes | Adds accessors to the published set, same as `protected $appends`. |
|
|
846
|
+
| `#[Connection('name')]` | Yes | Selects which database connection's schema the columns are read from, same as `protected $connection`. |
|
|
847
|
+
| `#[Collects(SomeResource::class)]` | Yes | Which resource a collection collects — see [API Resources](./api-resources.md). |
|
|
848
|
+
| `#[UseResource(...)]` / `#[UseResourceCollection(...)]` | Yes | Associates a model with its resource — see [API Resources](./api-resources.md). Available since Laravel 12.29, not just 13. |
|
|
849
|
+
| `#[PreserveKeys]` | Not yet | Would make a resource collection emit a keyed object instead of an array. No effect on generated output currently. |
|
|
850
|
+
| `#[RouteKey('slug')]` | **No** | Looks route-model-binding-relevant, but this package's route-argument inference does not currently call `getRouteKeyName()` for a model that only carries this attribute (as opposed to overriding the method itself), so a route bound by `#[RouteKey]` alone still generates its argument as keyed by `id`. Override `getRouteKeyName()` directly if you need the generated route helper to reflect a custom route key. |
|
|
851
|
+
| Everything else (`#[DateFormat]`, `#[WithoutTimestamps]`, `#[WithoutIncrementing]`, `#[Fillable]`, `#[Guarded]`, `#[Unguarded]`, `#[Scope]`, `#[ScopedBy]`, `#[ObservedBy]`, `#[Boot]`, `#[Initialize]`, `#[Touches]`, `#[CollectedBy]`, `#[UseEloquentBuilder]`, `#[UseFactory]`, `#[UsePolicy]`) | N/A | These affect querying, events, mass assignment, or factories — not the serialized shape — so there's nothing for the TypeScript generator to do either way. |
|
|
852
|
+
|
|
853
|
+
Most of these attribute classes (`#[Table]`, `#[Hidden]`, `#[Visible]`, `#[Appends]`, `#[Connection]`, `#[Collects]`, `#[PreserveKeys]`) require Laravel 13; `#[UseResource]`/`#[UseResourceCollection]` only require 12.29+. On an older floor, using one isn't a hard error — a `use` import of a nonexistent class doesn't fail until something actually resolves it, and nothing in this package or in Laravel itself does for a class-level attribute on a model that floor doesn't know about. The model loads and instantiates normally; the attribute is just silently ignored, which is a more dangerous failure mode than an error, since nothing tells you `#[Table]` didn't take effect. Stay on the version each attribute actually needs if you rely on it.
|
|
854
|
+
|
|
855
|
+
### Typing Attributes Without #[TsCasts]
|
|
856
|
+
|
|
857
|
+
#### Typing `array` casts with `@property`
|
|
858
|
+
|
|
859
|
+
A column cast to `'array'` (or any other cast the accessor → cast → DB waterfall can't type more precisely) generates as `unknown[]`. Rather than reaching for `#[TsCasts]`, add a class-level `@property`/`@property-read` docblock tag naming the real shape — the same convention PHPStan/Larastan already read — and it wins wherever the resolved type would otherwise stay vague:
|
|
860
|
+
|
|
861
|
+
```php
|
|
862
|
+
/**
|
|
863
|
+
* @property array<int, string>|null $to
|
|
864
|
+
* @property array<string, string>|null $headers
|
|
865
|
+
*/
|
|
866
|
+
class Message extends Model { ... }
|
|
867
|
+
```
|
|
868
|
+
|
|
869
|
+
`$to` and `$headers` now generate as `string[] | null` and `Record<string, string> | null` instead of `unknown[] | null` — and it types the same property for PHPStan/Larastan too. The tag only takes effect when the waterfall's own result is vague, so it never overrides a type already resolved specifically (an accessor's return type, an enum cast, a custom `CastsAttributes` class, etc.), and a subclass's own tag wins over one declared on a parent.
|
|
870
|
+
|
|
871
|
+
A refinement that's still partly vague is accepted as long as it's more structured than a bare untyped array/collection/object — `@property array<string, mixed>|null $settings` refines a plain `'array'` cast to `Record<string, unknown> | null` even though `Record<string, unknown>` itself still names `unknown`, because it beats the `unknown[]` it replaces. A refinement that's exactly as vague as the original (`unknown`, `unknown[]`, `object`, or the `unknown[] | Record<string, unknown>` Collection fallback) is still rejected.
|
|
872
|
+
|
|
873
|
+
The `@property` walk also covers every **trait** used by the class or its parents (recursively), so a trait supplying an accessor can carry its own class-level tag — including the non-standard `@property string[] labels` form some packages use without the `$` sigil.
|
|
874
|
+
|
|
875
|
+
#### Typing json columns with `@phpstan-type` aliases
|
|
876
|
+
|
|
877
|
+
For a shape complex enough to deserve a name, define it once as a `@phpstan-type` on the DTO that owns it, then pull it into the model with `@phpstan-import-type`:
|
|
878
|
+
|
|
879
|
+
```php
|
|
880
|
+
/** @phpstan-type PresetConfig array{filters?: array<string, mixed>, sorts?: list<string>} */
|
|
881
|
+
final readonly class PresetDto { ... }
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* @phpstan-import-type PresetConfig from PresetDto
|
|
885
|
+
* @property PresetConfig|null $config
|
|
886
|
+
*/
|
|
887
|
+
class Preset extends Model { ... }
|
|
888
|
+
```
|
|
889
|
+
|
|
890
|
+
`$config` generates as `{ filters?: Record<string, unknown>; sorts?: string[] } | null` — the alias expands inline (no import of `PresetDto` itself is emitted, since only its shape is used), optional keys keep their `?`, and PHPStan validates the same alias. `@phpstan-import-type ... as Alias` and `@psalm-type`/`@psalm-import-type` are both recognized, an alias may reference another imported alias, and a cyclical import degrades to `unknown` rather than hanging the publish run. This is the preferred path over `#[TsCasts]` for a shape that's already worth documenting for static analysis.
|
|
891
|
+
|
|
892
|
+
#### Typing castable-with-arguments casts
|
|
893
|
+
|
|
894
|
+
Laravel's built-in `Castable` classes carry their configuration after a colon — `AsEnumCollection::of(DayOfWeek::class)` and `AsCollection::of(...)`/`::using(...)` all build a `"ClassName:arg1,arg2"` cast string. These are resolved without any extra config:
|
|
895
|
+
|
|
896
|
+
```php
|
|
897
|
+
protected function casts(): array
|
|
898
|
+
{
|
|
899
|
+
return [
|
|
900
|
+
'week_days' => AsEnumCollection::of(DayOfWeek::class),
|
|
901
|
+
'grid_configs' => AsCollection::of(GridConfigDto::class),
|
|
902
|
+
];
|
|
903
|
+
}
|
|
904
|
+
```
|
|
905
|
+
|
|
906
|
+
- **`AsEnumCollection::of($enum)`** generates as the enum's TypeScript type suffixed `[]` — `DayOfWeekType[]` — with the enum's import wired exactly like a scalar enum-typed column.
|
|
907
|
+
- **`AsCollection::of($map)` / `::using($collection, $map)`** resolves the mapped class's element shape and appends `[]`. An `Arrayable` DTO with a documented `toArray()` shape inlines as an object array (`{ label: string; config: Record<string, unknown> }[]`); a mapped enum resolves the same way `AsEnumCollection` does. Without a resolvable map (or a bare `AsCollection`/`AsCollection::class`), it stays `unknown[]` — the same fallback as today.
|
|
908
|
+
- **Any other `Castable`/`CastsAttributes` class carrying arguments** — a custom cast, `AsEncryptedCollection`, etc. — resolves as if the arguments weren't there, i.e. exactly like the bare class.
|
|
909
|
+
|
|
910
|
+
Before reaching for `#[TsCasts]`, prefer — in this order — a parameterized `Attribute<>`/`@return`/`@phpstan-return` docblock on an accessor (generics included, e.g. `Attribute<Collection<int, LineItem>, never>`), a class-level `@property`/`@property-read` tag (including a `@phpstan-type`/`@phpstan-import-type` alias, as above), or a `@return MorphTo<A|B, $this>` generic on a `morphTo()` relation. All of these are read by PHPStan/Larastan too, so they're checked by static analysis in a way a package-specific attribute isn't — and every one is honored by the generator with no extra configuration. See the [annotation checklist](#annotation-checklist) below for the full symptom-first list.
|
|
911
|
+
|
|
912
|
+
`#[TsCasts]` is still the right tool when a shape is genuinely dynamic (keys built at runtime) or the type is owned by the frontend and needs its own import.
|
|
913
|
+
|
|
914
|
+
#### Typing `morphTo` relations
|
|
915
|
+
|
|
916
|
+
A `morphTo()` relation's target union is normally inferred in reverse — by scanning every other model for a `morphOne`/`morphMany` pointing back at it — which can only ever find a union, never narrow one. A `@return MorphTo<A|B, $this>` docblock generic on the relation method overrides that scan and types the relation directly, PHPStan-checked, no `#[TsCasts]` needed:
|
|
917
|
+
|
|
918
|
+
```php
|
|
919
|
+
class Activity extends Model
|
|
920
|
+
{
|
|
921
|
+
/** @return MorphTo<User, $this> */
|
|
922
|
+
public function causer(): MorphTo
|
|
923
|
+
{
|
|
924
|
+
return $this->morphTo();
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
```
|
|
928
|
+
|
|
929
|
+
`causer` generates as `User | null` even though no other model declares a reverse relation pointing at `Activity`. The second generic argument (`$this`, Laravel's own convention for the child) carries no target information and is ignored. A generic naming the base `Model` class (`MorphTo<Model, $this>`) isn't narrowing — it's the common, useless case (`@phpstan-return MorphTo<Model, $this>` is what Larastan itself expects when a relation's targets aren't known upfront) — so it falls through to the reverse scan exactly as if no generic were present, rather than emitting a `Model` token nothing can import. Two differently-named `morphTo` relations on the same model resolve independently either way, since both the docblock generic and the reverse scan are read per relation, not per model.
|
|
930
|
+
|
|
931
|
+
#### DTO-typed accessors and casts
|
|
932
|
+
|
|
933
|
+
An `Arrayable` DTO whose `toArray()` carries no `@return array{...}` shape now infers its shape from its own typed public properties — promoted constructor properties included — instead of falling back to `unknown[]`:
|
|
934
|
+
|
|
935
|
+
```php
|
|
936
|
+
final readonly class OrderTypeCapabilities implements Arrayable
|
|
937
|
+
{
|
|
938
|
+
public function __construct(
|
|
939
|
+
public string $typeName,
|
|
940
|
+
public bool $tracksSteelDetails,
|
|
941
|
+
public ?string $warehouseDocsKey = null,
|
|
942
|
+
) {}
|
|
943
|
+
|
|
944
|
+
/** @return array<string, bool|string|null> */
|
|
945
|
+
public function toArray(): array
|
|
946
|
+
{
|
|
947
|
+
return (array) $this;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
```
|
|
951
|
+
|
|
952
|
+
generates as `{ typeName: string; tracksSteelDetails: boolean; warehouseDocsKey: string | null }`. Nullable properties keep their `| null`; private, protected, and static properties are excluded, since they aren't part of `(array) $this`; and a property typed as a class with no import channel (a Model, for example) degrades to `unknown` the same way an unimportable docblock shape value does. Reach for a `@return array{...}` docblock instead only when the properties alone don't tell the whole story — it still wins whenever present.
|
|
953
|
+
|
|
954
|
+
This is `Arrayable`-only. A `JsonSerializable` DTO's `jsonSerialize()` still only resolves from a `@return array{...}` docblock and otherwise falls through to later resolution steps (e.g. its class basename), rather than inferring from properties — `(array) $this` is a real contract tying `toArray()` to a DTO's own properties, but `jsonSerialize()` can return anything, so inferring its shape from properties could produce a confidently wrong type.
|
|
955
|
+
|
|
956
|
+
#### What gets published: hidden attributes, write-only accessors
|
|
957
|
+
|
|
958
|
+
Not every attribute Eloquent knows about ends up in the generated interface:
|
|
959
|
+
|
|
960
|
+
- **`$hidden` attributes are published by default.** Setting `ts-publish.models.exclude_hidden` to `true` excludes them instead, matching Laravel's own `toArray()`/`toJson()` serialization — the rule that would then keep a `password` or `remember_token` column out of the model's own interface, and out of any resource property set that derives from the model implicitly (whole-model delegation, `except()` — see [API Resources § `exclude_hidden` and attribute filters](./api-resources.md#exclude-hidden-and-attribute-filters) for the full, deliberately asymmetric rule, since a resource's `only(['password'])` keeps a hidden column it named explicitly). The default is permissive (`false`, hidden attributes shown) so upgrading the package never silently drops a property a consuming app already relies on; opt in once you've confirmed the frontend doesn't need those columns. When the setting is enabled, an app that still needs a hidden column client-side should either drop it from `$hidden` or call `makeVisible()` before returning the model — the generator has no way to see a runtime `makeVisible()` call, so a hidden column drops from the model's own published interface regardless of any particular request.
|
|
961
|
+
- **Write-only mutators** — `Attribute::make(set: ...)` with no `get:` — resolve in this order: (1) the method's own `@return Attribute<Get, Set>` docblock, when the `Get` type is present and isn't itself vague; (2) a same-named database column, if one exists; (3) otherwise the mutator is omitted from the interface entirely, rather than emitted as `unknown`.
|
|
962
|
+
|
|
963
|
+
```php
|
|
964
|
+
class Order extends Model
|
|
965
|
+
{
|
|
966
|
+
/** @return Attribute<?string, string> */
|
|
967
|
+
protected function trackingCode(): Attribute
|
|
968
|
+
{
|
|
969
|
+
return Attribute::make(set: fn (string $value): string => strtoupper($value));
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
// No getter, no docblock generic, no backing column — omitted from OrderMutators entirely.
|
|
973
|
+
protected function searchIndex(): Attribute
|
|
974
|
+
{
|
|
975
|
+
return Attribute::make(set: fn (string $value): string => strtolower($value));
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
```
|
|
979
|
+
|
|
980
|
+
`trackingCode` generates as `tracking_code: string | null` in `OrderMutators`; `searchIndex` doesn't appear there at all. A write-only mutator backed by a real column (e.g. one that normalizes a value on save) resolves through the normal column waterfall instead, and is published as a column rather than a mutator.
|
|
981
|
+
|
|
982
|
+
#### Annotation checklist
|
|
983
|
+
|
|
984
|
+
A symptom-first index of the annotations above (plus one from [API Resources](./api-resources.md) on the API Resources page) — none of these need `#[TsCasts]`, and every one is read by PHPStan/Larastan too, so the annotation that unlocks the TypeScript type is also checked by static analysis:
|
|
985
|
+
|
|
986
|
+
| Still generating `unknown`? | Add this | Unlocks |
|
|
987
|
+
| -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
988
|
+
| `Attribute<Collection, never>` / `Attribute<array, never>` resolving to `unknown[]` | Parameterize the generic: `Attribute<Collection<int, LineItem>, never>` / `Attribute<array<int, string>, never>` (or `array{...}` for a fixed shape) | The real element type (`LineItem[]` / `string[]`), imported automatically |
|
|
989
|
+
| A bare `'array'`/`'collection'` cast with no shape anywhere else | A class-level `@property`/`@property-read` tag, e.g. `@property array<string, mixed>\|null $settings` | `Record<string, unknown> \| null` (or more specific, if the tag is) instead of `unknown[] \| null` — see [Typing `array` casts with `@property`](#typing-array-casts-with-property) |
|
|
990
|
+
| A JSON shape worth naming once and reusing | `@phpstan-type Name array{...}` on the class that owns it, `@phpstan-import-type Name from ThatClass` + `@property Name $prop` on the model | A named, PHPStan-checked object shape expanded inline, no import of the DTO itself — see [Typing json columns with `@phpstan-type` aliases](#typing-json-columns-with-phpstan-type-aliases) |
|
|
991
|
+
| `AsEnumCollection`/`AsCollection` cast with no argument, resolving to `unknown[]` | Pass the mapped class: `AsEnumCollection::of(Status::class)`, `AsCollection::of(LineItemDto::class)` | The mapped element's real type (enum or DTO shape), suffixed `[]` — see [Typing castable-with-arguments casts](#typing-castable-with-arguments-casts) |
|
|
992
|
+
| `morphTo()` typed `unknown \| null` even though the app knows the possible targets | `@return MorphTo<A\|B, $this>` on the relation method | The narrowed union, every member imported — see [Typing `morphTo` relations](#typing-morphto-relations) |
|
|
993
|
+
| An `Arrayable` DTO accessor/cast generating `unknown[]` | Nothing extra — typed public properties (promoted constructor properties included) are read automatically once `toArray()` has no `@return array{...}` shape of its own | A property-derived object shape instead of `unknown[]` — see [DTO-typed accessors and casts](#dto-typed-accessors-and-casts) |
|
|
994
|
+
| `$this->relation->only([...])`/`->except([...])` losing the related model's own `#[TsCasts]`/`@property` refinements | Nothing extra — automatic whenever every filtered key is a real database column | `Pick<Model, 'a' \| 'b'>` / `Omit<Model, ...>` referencing the model's own generated interface — see [API Resources](./api-resources.md) |
|
|
995
|
+
|
|
836
996
|
### PHPDoc Descriptions
|
|
837
997
|
|
|
838
998
|
Doc blocks are read automatically and converted to JSDoc comments:
|
|
@@ -893,36 +1053,78 @@ The default PHP-to-TypeScript mapping is intentionally broad. Override or extend
|
|
|
893
1053
|
|
|
894
1054
|
Custom mappings are merged with the built-in map and take precedence. For a _per-property_ override instead of a global one, use [`#[TsCasts]`](#tscasts) or [`#[TsType]`](#tstype) instead.
|
|
895
1055
|
|
|
1056
|
+
Only the display-width-1 form stays boolean. `tinyint(1)` is what Laravel's `boolean()` emits on
|
|
1057
|
+
MySQL and SQLite, so genuine boolean columns are unaffected — but a column declared with
|
|
1058
|
+
`tinyInteger()` was previously typed [`boolean`](#booleans) and is now [`number`](#numbers).
|
|
1059
|
+
|
|
1060
|
+
Previously, a sized native type never matched the map at all and fell through to a substring scan,
|
|
1061
|
+
which matched `int` inside `tinyint(1)` before reaching `tinyint`. That is why some genuinely boolean
|
|
1062
|
+
columns were also mistyped before this change.
|
|
1063
|
+
|
|
1064
|
+
**What to do:** anywhere you compared a `tinyInteger()` column with `=== true` or used it directly in
|
|
1065
|
+
a conditional, compare against the number instead. TypeScript will point at every site.
|
|
1066
|
+
|
|
1067
|
+
`AsArrayObject`, `AsEncryptedArrayObject` and `AsEnumArrayObject` now emit
|
|
1068
|
+
[`unknown[] | Record<string, unknown>`](#arrays-objects) rather than `Record<string, unknown>` alone.
|
|
1069
|
+
|
|
1070
|
+
An `ArrayObject` hydrated from a list serializes as a JSON **array**, so the old type rejected a
|
|
1071
|
+
payload the API genuinely returns.
|
|
1072
|
+
|
|
1073
|
+
**What to do:** narrow before treating the value as an object. `Object.keys(x.meta)` no longer
|
|
1074
|
+
compiles on its own; guard with `Array.isArray(x.meta)` first, or use
|
|
1075
|
+
[`#[TsCasts]`](#tscasts) to pin the property to whichever half your column actually produces.
|
|
1076
|
+
|
|
896
1077
|
#### Type Mapping Reference
|
|
897
1078
|
|
|
898
1079
|
[Numbers](#numbers) [Booleans](#booleans) [Strings](#strings) [Arrays & Objects](#arrays-objects) [Dates & Times](#dates-times) [Other](#other)
|
|
899
1080
|
|
|
900
1081
|
##### Numbers
|
|
901
1082
|
|
|
902
|
-
`bigint`, `decimal`, `double`, `float`, `integer`, `int`, `numeric`, `number`, `mediumint`, `smallint`, `year`, `real` → **`number`**
|
|
1083
|
+
`bigint`, `decimal`, `double`, `double precision`, `float`, `integer`, `int`, `numeric`, `number`, `mediumint`, `smallint`, `year`, `real`, `money`, `smallmoney`, `serial`, `bigserial`, `smallserial` → **`number`**
|
|
1084
|
+
|
|
1085
|
+
A bare `tinyint` (MySQL/SQL Server `tinyInteger()`) is also **`number`** — only the display-width-1 form (`tinyint(1)`, Laravel's `boolean()` column on MySQL/SQLite) means boolean; see [Booleans](#booleans).
|
|
903
1086
|
|
|
904
1087
|
##### Booleans
|
|
905
1088
|
|
|
906
|
-
`bool`, `boolean`, `tinyint` → **`boolean`**
|
|
1089
|
+
`bool`, `boolean`, `bit`, `tinyint(1)` → **`boolean`**
|
|
907
1090
|
|
|
908
1091
|
##### Strings
|
|
909
1092
|
|
|
910
1093
|
`char`, `character`, `enum`, `longtext`, `mediumtext`, `string`, `text`, `varchar`, `encrypted`, `uuid`, `guid`, `hashed`, `time`, `timetz`, `timestamptz`, `numeric-string` → **`string`**
|
|
911
1094
|
|
|
1095
|
+
Sized, binary, and legacy DB native types resolve the same way: `tinytext`, `binary`, `varbinary`, `blob`, `bytea`, `tinyblob`, `mediumblob`, `longblob`, `nvarchar`, `nchar`, `ntext`, `xml`, `interval`, `uniqueidentifier`, `datetimeoffset` → **`string`**. `set(…)` also resolves to `string`, not an array — MySQL returns a matched `SET` as a comma-joined string. So do Postgres/MySQL's network and full-text types: `inet`, `cidr`, `macaddr`, `macaddr8`, `tsvector`.
|
|
1096
|
+
|
|
912
1097
|
##### Arrays & Objects
|
|
913
1098
|
|
|
914
|
-
| Cast
|
|
915
|
-
|
|
|
916
|
-
| `array`, `collection`
|
|
917
|
-
| `
|
|
918
|
-
| `
|
|
919
|
-
| `
|
|
920
|
-
| `Illuminate\
|
|
921
|
-
| `Illuminate\
|
|
1099
|
+
| Cast | TypeScript Type |
|
|
1100
|
+
| ------------------------------------------------------------------ | -------------------------------------- |
|
|
1101
|
+
| `array`, `collection`, `iterable` | `unknown[]` |
|
|
1102
|
+
| `AsCollection`, `AsEncryptedCollection`, `AsEnumCollection` (bare) | `unknown[]` |
|
|
1103
|
+
| `AsArrayObject`, `AsEncryptedArrayObject`, `AsEnumArrayObject` | `unknown[] \| Record<string, unknown>` |
|
|
1104
|
+
| `json`, `jsonb`, `object` | `object` |
|
|
1105
|
+
| `Illuminate\Database\Eloquent\Collection` | `Record<string, unknown>` |
|
|
1106
|
+
| `Illuminate\Support\Collection` | `unknown[] \| Record<string, unknown>` |
|
|
1107
|
+
| `Illuminate\Database\Eloquent\Casts\AsFluent` | `object` |
|
|
1108
|
+
|
|
1109
|
+
The three `As*ArrayObject` casts hydrate an `ArrayObject`, whose `jsonSerialize()` returns the underlying array verbatim — a list payload serializes as a JSON array, not an object, so the type admits both shapes rather than claiming `Record<string, unknown>` alone.
|
|
1110
|
+
|
|
1111
|
+
The `unknown[]` collection row above is the **bare** form. `AsEnumCollection::of(...)` and `AsCollection::of(...)` / `::using(...)` carry their mapped class in the cast string and resolve to that element's real type instead — see [Typing castable-with-arguments casts](#typing-castable-with-arguments-casts).
|
|
1112
|
+
|
|
1113
|
+
A parameterized docblock generic (`@return`, `@property`, `Attribute<>`) narrows further, based on its declared key type. The container and the key type are resolved independently, so every container behaves identically for a given key type:
|
|
1114
|
+
|
|
1115
|
+
| Key type | Emitted | Containers |
|
|
1116
|
+
| -------------------- | -------------------------- | ----------------------------------------------------- |
|
|
1117
|
+
| `int`, or omitted | `X[]` | `list<X>`, `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1118
|
+
| `string` | `Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1119
|
+
| `array-key`, `mixed` | `X[] \| Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1120
|
+
|
|
1121
|
+
(`list<X>` has no key-type slot at all — a `list<X>` docblock generic always resolves to the first row, `X[]`.) A container with **no generic at all** — a bare `Collection`, unparameterized — doesn't reach this table: it resolves through the [Arrays & Objects](#arrays-objects) table above, via `TypeScriptMap`, not through the docblock generic resolver.
|
|
1122
|
+
|
|
1123
|
+
A collection _chain_ on a relation (`->sortBy()`, `->pluck($value, $key)`, `->take()`, …) is analyzed separately from its declared type: it keeps the `X[] | Record<string, X>` union unless the chain provably ends with sequential, 0-indexed keys — e.g. a trailing `->values()`, or `->take()` anchored at the front of an already-sequential collection — in which case it narrows to `X[]`.
|
|
922
1124
|
|
|
923
1125
|
##### Dates & Times
|
|
924
1126
|
|
|
925
|
-
`date`, `immutable_date`, `datetime`, `immutable_datetime`, `immutable_custom_datetime`, `timestamp`, and Carbon
|
|
1127
|
+
`date`, `immutable_date`, `datetime`, `immutable_datetime`, `immutable_custom_datetime`, `timestamp`, `datetime2`, `smalldatetime`, and `Carbon`/`CarbonImmutable`/`Illuminate\Support\Carbon` casts all resolve through [`timestamps_as_date`](#timestamps-as-date-objects) → **`string`** (default) or **`Date`**. `datetime2` is what SQL Server's `dateTime($precision)`/`timestamp($precision)` actually emit once a precision is given — the same logical column as bare `datetime`, so it follows the same toggle; `smalldatetime` is kept consistent with it.
|
|
926
1128
|
|
|
927
1129
|
##### Other
|
|
928
1130
|
|
|
@@ -936,6 +1138,16 @@ Custom mappings are merged with the built-in map and take precedence. For a _per
|
|
|
936
1138
|
| `true` / `false` (PHPStan) | `true` / `false` |
|
|
937
1139
|
| `array-key` (PHPStan) | `string \| number` |
|
|
938
1140
|
| `scalar` (PHPStan) | `string \| number \| boolean` |
|
|
1141
|
+
| `geometry`, `geography` | `unknown` |
|
|
1142
|
+
| `vector` | `number[]` |
|
|
1143
|
+
|
|
1144
|
+
A spatial column's serialized shape depends entirely on how the app reads it — raw WKB is a binary
|
|
1145
|
+
string, `ST_AsGeoJSON()` is an object — so `unknown` is the honest type rather than a guess. `vector`
|
|
1146
|
+
is a pgvector/MySQL 9 column, which both serialize as a JSON array of floats.
|
|
1147
|
+
|
|
1148
|
+
MySQL's `geometry(subtype: '...')` writes the subtype itself as the column's native type instead of
|
|
1149
|
+
`geometry` — `point`, `linestring`, `polygon`, `geometrycollection`, `multipoint`, `multilinestring`,
|
|
1150
|
+
and `multipolygon` all resolve to **`unknown`** too, for the same reason as `geometry` above.
|
|
939
1151
|
|
|
940
1152
|
### Enum-Typed Columns (`{Model}Resource`)
|
|
941
1153
|
|
|
@@ -945,8 +1157,8 @@ A column, mutator, or relation typed to a `BackedEnum` or `UnitEnum` gets two re
|
|
|
945
1157
|
- A parallel `{Model}Resource` / `{Model}MutatorsResource` / `{Model}AllResource` interface types the same property with [`AsEnum<typeof Enum>`](./enums.md#type-reference) instead — the shape you get once you've resolved the raw value to a full enum instance (e.g. `Status.from(user.status)`, or a Laravel API Resource that already serialized the enum via [`EnumResource`](./enum-api-resource.md)).
|
|
946
1158
|
|
|
947
1159
|
```typescript
|
|
948
|
-
import { Role } from "@
|
|
949
|
-
import type { User, UserResource } from "@
|
|
1160
|
+
import { Role } from "@data/enums";
|
|
1161
|
+
import type { User, UserResource } from "@data/models";
|
|
950
1162
|
|
|
951
1163
|
function displayRole(user: User) {
|
|
952
1164
|
const resolved: UserResource["role"] = user.role
|
|
@@ -1041,22 +1253,130 @@ The analyzer recognizes the following patterns inside `toArray()`:
|
|
|
1041
1253
|
|
|
1042
1254
|
Types are resolved from the model's database columns and cast definitions.
|
|
1043
1255
|
|
|
1044
|
-
####
|
|
1256
|
+
#### Local Variables
|
|
1257
|
+
|
|
1258
|
+
A variable assigned once from a model property and returned directly carries that type into the generated interface — you don't need to inline the property access:
|
|
1259
|
+
|
|
1260
|
+
```php
|
|
1261
|
+
public function toArray(Request $request): array
|
|
1262
|
+
{
|
|
1263
|
+
$slug = $this->slug;
|
|
1264
|
+
|
|
1265
|
+
return [
|
|
1266
|
+
'slug' => $slug, // string — same as returning `$this->slug` directly
|
|
1267
|
+
];
|
|
1268
|
+
}
|
|
1269
|
+
```
|
|
1270
|
+
|
|
1271
|
+
This still works even if the same name is reused as a closure or arrow-function parameter elsewhere in the method. The parameter only shadows the variable for its own closure body — it no longer degrades the outer property to `unknown`:
|
|
1045
1272
|
|
|
1046
|
-
|
|
1273
|
+
```php
|
|
1274
|
+
public function toArray(Request $request): array
|
|
1275
|
+
{
|
|
1276
|
+
$member = $this->slug;
|
|
1277
|
+
|
|
1278
|
+
return [
|
|
1279
|
+
'outer_member' => $member, // string
|
|
1280
|
+
'mapped_members' => $this->members->map(fn ($member) => $member), // User[] — this $member is the map's own element
|
|
1281
|
+
];
|
|
1282
|
+
}
|
|
1283
|
+
```
|
|
1047
1284
|
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1285
|
+
If you see a property come out as `unknown` when it looks like it should resolve, check whether the backing variable is reassigned more than once, or reassigned inside a conditional branch — the analyzer can't tell which write is live at return time, so it deliberately falls back to `unknown` rather than guessing.
|
|
1286
|
+
|
|
1287
|
+
#### Conditional Methods
|
|
1288
|
+
|
|
1289
|
+
All conditional methods produce **optional** properties (with `?` in TypeScript) by default. Every one of
|
|
1290
|
+
them, though, accepts a trailing default argument — and passing it explicitly makes the property
|
|
1291
|
+
**required**, because the key can no longer be missing. `whenNotNull()`/`whenNull()`'s default argument is
|
|
1292
|
+
covered just below the table; the rest of the family is covered right after that.
|
|
1293
|
+
|
|
1294
|
+
| Method | Description | Generated Type |
|
|
1295
|
+
| ----------------------------------------------- | ---------------------------------------------- | ------------------------- |
|
|
1296
|
+
| `$this->when(cond, value)` | Include when condition is true | Inferred from value |
|
|
1297
|
+
| `$this->unless(cond, value)` | Include when condition is false | Inferred from value |
|
|
1298
|
+
| `$this->whenHas('attr')` | Include when attribute is present | From model column type |
|
|
1299
|
+
| `$this->whenAppended('attr')` | Include when accessor has been appended | From model column type |
|
|
1300
|
+
| `$this->whenNotNull($this->attr)` | Include when not null | From model column type |
|
|
1301
|
+
| `$this->whenNull($this->attr)` | Include when null | `null` |
|
|
1302
|
+
| `$this->whenLoaded('relation')` | Include when relation is loaded | From model relation type |
|
|
1303
|
+
| `$this->whenCounted('relation')` | Include when count is loaded | `number` |
|
|
1304
|
+
| `$this->whenAggregated('rel', 'col', 'fn')` | Include when aggregate is loaded | `number` |
|
|
1305
|
+
| `$this->whenExistsLoaded('relation')` | Include when existence flag is loaded | `boolean` |
|
|
1306
|
+
| `$this->whenPivotLoaded('table')` | Include when pivot is loaded | `unknown` |
|
|
1307
|
+
| `$this->whenPivotLoadedAs('accessor', 'table')` | Include when pivot (custom accessor) is loaded | `unknown` |
|
|
1308
|
+
| `$this->transform($value, $callback)` | Transform `$value` via `$callback` when filled | Inferred from `$callback` |
|
|
1057
1309
|
|
|
1058
1310
|
See [Nullable Relations](#nullable-relations) for `whenLoaded` nullability handling.
|
|
1059
1311
|
|
|
1312
|
+
##### `unless()` is `when()` with the condition negated
|
|
1313
|
+
|
|
1314
|
+
`unless($condition, $value, $default)` runs `$value` when `$condition` is **false** — everything else about
|
|
1315
|
+
how it's typed is identical to `when()`, including the default-argument rule covered below:
|
|
1316
|
+
|
|
1317
|
+
```php
|
|
1318
|
+
'status' => $this->unless($this->is_draft, $this->status), // optional
|
|
1319
|
+
'status' => $this->unless($this->is_draft, $this->status, 'draft'), // required
|
|
1320
|
+
```
|
|
1321
|
+
|
|
1322
|
+
##### `whenNotNull()` / `whenNull()` and their optional second argument
|
|
1323
|
+
|
|
1324
|
+
`whenNotNull($value, $default)` and `whenNull($value, $default)` read their arguments positionally — the
|
|
1325
|
+
second argument is Laravel's fallback value, never a callback bound to the first argument. `whenNotNull()`'s guard
|
|
1326
|
+
proves the value non-null on the success arm, so its `null` possibility is removed from the generated type:
|
|
1327
|
+
|
|
1328
|
+
```php
|
|
1329
|
+
'line_2' => $this->whenNotNull($this->line_2), // string | null column
|
|
1330
|
+
```
|
|
1331
|
+
|
|
1332
|
+
generates `line_2?: string`, not `line_2?: string | null`.
|
|
1333
|
+
|
|
1334
|
+
Passing a second argument changes both `optional` and the type: Laravel never omits the key once a default
|
|
1335
|
+
is supplied, so the property becomes **required**, and its type becomes the union of the value and default
|
|
1336
|
+
arms:
|
|
1337
|
+
|
|
1338
|
+
```php
|
|
1339
|
+
'discount' => $this->whenNotNull($this->discount_percent, 0), // discount_percent: number | null
|
|
1340
|
+
```
|
|
1341
|
+
|
|
1342
|
+
generates `discount: number` (required) — the default's type merges with, and here fully overlaps, the
|
|
1343
|
+
value's own type. A default of a different type (e.g. a string fallback for a numeric column) produces a
|
|
1344
|
+
union of both, still required.
|
|
1345
|
+
|
|
1346
|
+
##### The rest of the conditional family and their default argument
|
|
1347
|
+
|
|
1348
|
+
The same rule applies to every other conditional method: pass a default and the property stops being
|
|
1349
|
+
optional, because it can no longer be missing.
|
|
1350
|
+
|
|
1351
|
+
```php
|
|
1352
|
+
'status' => $this->when($this->is_published, $this->status), // optional
|
|
1353
|
+
'status' => $this->when($this->is_published, $this->status, 'draft'), // required
|
|
1354
|
+
```
|
|
1355
|
+
|
|
1356
|
+
The type widens too, whenever the generator can resolve the default: its type is unioned in alongside the
|
|
1357
|
+
value's, so the property covers both arms rather than only the one the value expression named.
|
|
1358
|
+
|
|
1359
|
+
```php
|
|
1360
|
+
'discount' => $this->when($this->has_discount, $this->discount_percent), // discount?: number
|
|
1361
|
+
'discount' => $this->when($this->has_discount, $this->discount_percent, 'n/a'), // discount: number | string
|
|
1362
|
+
'reviews' => $this->whenCounted('reviews', null, 'n/a'), // reviews: number | string
|
|
1363
|
+
'address' => $this->whenHas('full_address', $this->full_address, 0), // address: string | number
|
|
1364
|
+
```
|
|
1365
|
+
|
|
1366
|
+
An explicit `null` still counts as a default — Laravel distinguishes an omitted argument from a passed-in
|
|
1367
|
+
one, not a `null` value from a non-null one — so
|
|
1368
|
+
`$this->whenLoaded('user', fn ($user) => $user, null)` is required, and typed `User | null` rather than a
|
|
1369
|
+
bare `User` you could dereference on the not-loaded path.
|
|
1370
|
+
|
|
1371
|
+
The property is required either way — passing a default means the key is always there. Only the _type_
|
|
1372
|
+
depends on what the generator could resolve, and two cases can't be widened:
|
|
1373
|
+
|
|
1374
|
+
- **The default's own type can't be resolved** (an unanalyzable expression or closure). There is nothing to
|
|
1375
|
+
union in, so the value's type stands alone.
|
|
1376
|
+
- **The value's type can't be resolved** — `whenPivotLoaded()` and `whenPivotLoadedAs()`, whose pivot
|
|
1377
|
+
payload the generator never inspects. The property stays `unknown`, since `unknown` already admits the
|
|
1378
|
+
default.
|
|
1379
|
+
|
|
1060
1380
|
#### Enum Properties with `EnumResource`
|
|
1061
1381
|
|
|
1062
1382
|
Use `EnumResource::make()` to expose enum-cast properties as rich enum objects:
|
|
@@ -1097,7 +1417,7 @@ Self-referencing resources are also supported:
|
|
|
1097
1417
|
|
|
1098
1418
|
#### Merge Operations
|
|
1099
1419
|
|
|
1100
|
-
Use `merge` and `
|
|
1420
|
+
Use `merge`, `mergeWhen`, and `mergeUnless` to spread additional properties into the response:
|
|
1101
1421
|
|
|
1102
1422
|
```php
|
|
1103
1423
|
// Unconditional merge — properties are required (not optional)
|
|
@@ -1128,10 +1448,11 @@ $this->mergeWhen($this->paid_at !== null, fn () => [
|
|
|
1128
1448
|
]),
|
|
1129
1449
|
```
|
|
1130
1450
|
|
|
1131
|
-
| Method
|
|
1132
|
-
|
|
|
1133
|
-
| `$this->merge([...])`
|
|
1134
|
-
| `$this->mergeWhen(cond, [...])`
|
|
1451
|
+
| Method | Optionality | Description |
|
|
1452
|
+
| --------------------------------- | -------------- | ---------------------------------------- |
|
|
1453
|
+
| `$this->merge([...])` | Required | Properties are always present |
|
|
1454
|
+
| `$this->mergeWhen(cond, [...])` | Optional (`?`) | Properties included conditionally |
|
|
1455
|
+
| `$this->mergeUnless(cond, [...])` | Optional (`?`) | Properties included when `cond` is false |
|
|
1135
1456
|
|
|
1136
1457
|
#### Closure & Arrow Function Values
|
|
1137
1458
|
|
|
@@ -1270,6 +1591,54 @@ trait IncludesExtras
|
|
|
1270
1591
|
> [!NOTE]
|
|
1271
1592
|
> When a trait method has no `@return array{...}` PHPDoc or `#[TsCasts]` attribute, its properties will be typed as `unknown`.
|
|
1272
1593
|
|
|
1594
|
+
#### Bare Method-Call Return
|
|
1595
|
+
|
|
1596
|
+
`toArray()` doesn't have to spread a method's return value into an array literal — returning the method call directly is supported too:
|
|
1597
|
+
|
|
1598
|
+
```php
|
|
1599
|
+
public function toArray(Request $request): array
|
|
1600
|
+
{
|
|
1601
|
+
return $this->data(); // now supported
|
|
1602
|
+
// return [...$this->data()]; // already supported
|
|
1603
|
+
}
|
|
1604
|
+
```
|
|
1605
|
+
|
|
1606
|
+
This resolves transitively: if `data()` itself returns another method call, the analyzer keeps following the chain until it reaches an array literal (or an `only()`/`except()` filter — see [Attribute Filters](#attribute-filters-only--except) below):
|
|
1607
|
+
|
|
1608
|
+
```php
|
|
1609
|
+
class TeamResource extends JsonResource
|
|
1610
|
+
{
|
|
1611
|
+
public function toArray(Request $request): array
|
|
1612
|
+
{
|
|
1613
|
+
return $this->data();
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
protected function data(): array
|
|
1617
|
+
{
|
|
1618
|
+
return $this->nested();
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
protected function nested(): array
|
|
1622
|
+
{
|
|
1623
|
+
return [
|
|
1624
|
+
'id' => $this->id,
|
|
1625
|
+
'slug' => $this->slug,
|
|
1626
|
+
];
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
```
|
|
1630
|
+
|
|
1631
|
+
Generates:
|
|
1632
|
+
|
|
1633
|
+
```typescript
|
|
1634
|
+
export interface TeamResource {
|
|
1635
|
+
id: number;
|
|
1636
|
+
slug: string;
|
|
1637
|
+
}
|
|
1638
|
+
```
|
|
1639
|
+
|
|
1640
|
+
The chain can pass through a trait and parent-declared methods the same way a `...$this->method()` spread does — see [Trait Method Spread](#trait-method-spread) above.
|
|
1641
|
+
|
|
1273
1642
|
#### JsonResource Base Delegation
|
|
1274
1643
|
|
|
1275
1644
|
Resources that have **no `toArray()` method** or whose `toArray()` simply returns `parent::toArray($request)` automatically generate properties from the backing model's database schema:
|
|
@@ -1330,6 +1699,31 @@ Both methods delegate to the backing model's full database schema and filter by
|
|
|
1330
1699
|
> [!NOTE]
|
|
1331
1700
|
> Currently only `only` and `except` are supported as attribute filter methods. Other collection-style methods are not analyzed. If you find you need additional methods, open an issue, or better yet, submit a PR with the added functionality! See [`FiltersModelAttributes`](https://github.com/abetwothree/laravel-ts-publish/blob/main/src/Analyzers/Concerns/FiltersModelAttributes.php).
|
|
1332
1701
|
|
|
1702
|
+
#### `exclude_hidden` and attribute filters
|
|
1703
|
+
|
|
1704
|
+
`ts-publish.models.exclude_hidden` (see [Models § What gets published](./models.md#what-gets-published-hidden-attributes-write-only-accessors)) governs resources too, not just the model's own interface:
|
|
1705
|
+
|
|
1706
|
+
```php
|
|
1707
|
+
$this->only(['password']) // kept: you named it
|
|
1708
|
+
$this->except(['id']) // password dropped: the set is derived
|
|
1709
|
+
```
|
|
1710
|
+
|
|
1711
|
+
That split isn't arbitrary — it mirrors what `Model::only()` versus `toArray()`/`except()` already do at runtime. `Model::only()` resolves each key through `getAttribute()`, which returns a `$hidden` attribute regardless of visibility; `toArray()` and `Model::except()` both go through `getArrayableItems()`, which strips `$hidden` attributes before your excluded keys are even considered. This package's analyzer follows the same split:
|
|
1712
|
+
|
|
1713
|
+
| Pattern | Property set | A `$hidden` column, with `exclude_hidden` enabled |
|
|
1714
|
+
| --------------------------------------------------------------------------------------- | ------------------------------------------ | ------------------------------------------------- |
|
|
1715
|
+
| `'password' => $this->password` | the property you wrote by hand | **kept** — you named it |
|
|
1716
|
+
| `$this->only(['id', 'password'])` | exactly the keys you named | **kept** — you named it |
|
|
1717
|
+
| `$this->relation->only(['id', 'password'])` | exactly the keys you named | **kept** — you named it |
|
|
1718
|
+
| `$this->whenHas('password')` | the attribute you named | **kept** — you named it |
|
|
1719
|
+
| `$this->except(['id'])` | every model attribute minus the named keys | **dropped** — the set is derived |
|
|
1720
|
+
| `$this->relation->except(['id'])` | every attribute minus the named keys | **dropped** — the set is derived |
|
|
1721
|
+
| `parent::toArray($request)`, `[...parent::toArray($request)]`, or no `toArray()` at all | every model attribute | **dropped** — the set is derived |
|
|
1722
|
+
|
|
1723
|
+
`'password' => $this->password` is worth calling out on its own: it's the plainest, most common way to expose a column, and it behaves exactly like a named `only()` key — a `$hidden` column you access directly is never silently dropped.
|
|
1724
|
+
|
|
1725
|
+
If you want a `$hidden` column published through one of the derived paths, name it explicitly — switch that property to `only([...])`, access it directly as `$this->column`, or drop it from the model's `$hidden` array entirely if it no longer needs to be hidden.
|
|
1726
|
+
|
|
1333
1727
|
#### Resource Collections
|
|
1334
1728
|
|
|
1335
1729
|
`ResourceCollection` subclasses are supported. The analyzer resolves `$this->collection` to the singular resource type as an array:
|
|
@@ -1382,6 +1776,42 @@ class OrderCollection extends ResourceCollection
|
|
|
1382
1776
|
|
|
1383
1777
|
When the singular resource cannot be resolved (e.g., `MiscCollection` with no matching `MiscResource`), `$this->collection` falls back to `unknown`.
|
|
1384
1778
|
|
|
1779
|
+
##### Key-Preserving Collections
|
|
1780
|
+
|
|
1781
|
+
A `ResourceCollection` normally serializes as a JSON array, so the generated type is `R[]`. Laravel
|
|
1782
|
+
supports opting a collection out of that and keeping its original keys instead, which makes the
|
|
1783
|
+
payload a JSON object — two ways to opt in, both recognized:
|
|
1784
|
+
|
|
1785
|
+
```php
|
|
1786
|
+
use Illuminate\Http\Resources\Attributes\PreserveKeys;
|
|
1787
|
+
use Illuminate\Http\Resources\Json\ResourceCollection;
|
|
1788
|
+
|
|
1789
|
+
#[PreserveKeys] // Laravel 13+
|
|
1790
|
+
class TeamCollection extends ResourceCollection
|
|
1791
|
+
{
|
|
1792
|
+
public $collects = TeamResource::class;
|
|
1793
|
+
}
|
|
1794
|
+
```
|
|
1795
|
+
|
|
1796
|
+
```php
|
|
1797
|
+
use Illuminate\Http\Resources\Json\ResourceCollection;
|
|
1798
|
+
|
|
1799
|
+
class TeamCollection extends ResourceCollection
|
|
1800
|
+
{
|
|
1801
|
+
public $preserveKeys = true; // works on every supported Laravel version
|
|
1802
|
+
|
|
1803
|
+
public $collects = TeamResource::class;
|
|
1804
|
+
}
|
|
1805
|
+
```
|
|
1806
|
+
|
|
1807
|
+
Either form generates:
|
|
1808
|
+
|
|
1809
|
+
```typescript
|
|
1810
|
+
export interface TeamCollection {
|
|
1811
|
+
data: Record<string, TeamResource>;
|
|
1812
|
+
}
|
|
1813
|
+
```
|
|
1814
|
+
|
|
1385
1815
|
Larger support for `ResourceCollection` features (e.g., pagination metadata, `additional()` method, etc.) may be added in a future release.
|
|
1386
1816
|
|
|
1387
1817
|
### Anatomy of a Generated Resource
|
|
@@ -1437,7 +1867,7 @@ export interface UserResource {
|
|
|
1437
1867
|
profile?: Profile | null;
|
|
1438
1868
|
posts?: PostResource[];
|
|
1439
1869
|
phone?: string | null;
|
|
1440
|
-
avatar?: string
|
|
1870
|
+
avatar?: string;
|
|
1441
1871
|
posts_count?: number;
|
|
1442
1872
|
comments_count?: number;
|
|
1443
1873
|
}
|
|
@@ -1636,7 +2066,7 @@ Or publish only resources for a single run using the command flag:
|
|
|
1636
2066
|
php artisan ts:publish --only-resources
|
|
1637
2067
|
```
|
|
1638
2068
|
|
|
1639
|
-
The `--only-resources` flag cannot be combined with `--only-enums
|
|
2069
|
+
The `--only-resources` flag cannot be combined with any other `--only-*` flag (`--only-enums`, `--only-models`, `--only-routes`, `--only-form-requests`, `--only-broadcast-channels`, `--only-broadcast-events`).
|
|
1640
2070
|
|
|
1641
2071
|
### Configuration Reference
|
|
1642
2072
|
|
|
@@ -2997,7 +3427,6 @@ export interface StorePostRequest {
|
|
|
2997
3427
|
/** @format email */
|
|
2998
3428
|
email: string;
|
|
2999
3429
|
tags?: string[];
|
|
3000
|
-
"tags.*"?: string;
|
|
3001
3430
|
}
|
|
3002
3431
|
```
|
|
3003
3432
|
|
|
@@ -3006,7 +3435,7 @@ export interface StorePostRequest {
|
|
|
3006
3435
|
- `rating` demonstrates that a [`#[TsCasts]`](#tscasts-overriding-field-types) override only replaces the _type_ and _optionality_ — the `nullable` rule's `| null` suffix is still appended by the analyzer afterward, giving `number | bigint | null` rather than just `number | bigint`.
|
|
3007
3436
|
- `email` picks up a [JSDoc metadata annotation](#jsdoc-metadata-annotations) (`@format email`) from the `email` rule.
|
|
3008
3437
|
- `tags` is upgraded from the bare `array` rule's `unknown[]` to `string[]` — first automatically (from the sibling `tags.*` wildcard rule), then explicitly overridden to the same value by `#[TsCasts]`.
|
|
3009
|
-
- `
|
|
3438
|
+
- `tags.*` does **not** get a property of its own. A dot-notation or wildcard rule key describes a value _inside_ `tags`, so it composes into `tags` instead of being emitted alongside it as a quoted `"tags.*"` key — see [Array & Nested Rules](#array-nested-rules).
|
|
3010
3439
|
- The class docblock (none here) would become the interface's JSDoc comment; individual fields don't support their own docblocks since they come from array keys inside `rules()`, not separate PHP declarations — the [JSDoc metadata annotations](#jsdoc-metadata-annotations) fill that role instead.
|
|
3011
3440
|
|
|
3012
3441
|
### Rule-to-Type Mapping Reference
|
|
@@ -3041,16 +3470,16 @@ Rules are checked in this order — the first match wins:
|
|
|
3041
3470
|
|
|
3042
3471
|
##### Arrays
|
|
3043
3472
|
|
|
3044
|
-
`array`, `list` → **`unknown[]`** (upgraded to `T[]` automatically when a sibling `field.*` wildcard rule resolves to type `T` — see [Array & Nested Rules](#array-nested-rules))
|
|
3473
|
+
`array`, `list` → **`unknown[]`** (upgraded to `T[]` automatically when a sibling `field.*` wildcard rule resolves to type `T` — see [Array & Nested Rules](#array-nested-rules); upgraded to a keyed object instead when `required_array_keys`/`in_array_keys`/`array:` names its keys — see [Key-list rules](#key-list-rules-known-keys-without-a-full-shape))
|
|
3045
3474
|
|
|
3046
3475
|
### Presence, Nullability & Exclusion
|
|
3047
3476
|
|
|
3048
|
-
| Rule | Effect
|
|
3049
|
-
| ---------------------------------------------------------------------------------------------------- |
|
|
3050
|
-
| `required` (or any rule starting with `required`, including `Rule::requiredIf()`/`requiredUnless()`) | Field is **required** (no `?`)
|
|
3051
|
-
| `sometimes` | Field is optional, even combined with `required`
|
|
3052
|
-
| `nullable` | Adds `\| null` to the field's type
|
|
3053
|
-
| `missing` / `prohibited` | Field is **excluded from the interface entirely** — not just marked optional |
|
|
3477
|
+
| Rule | Effect |
|
|
3478
|
+
| ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
3479
|
+
| `required` (or any rule starting with `required`, including `Rule::requiredIf()`/`requiredUnless()`) | Field is **required** (no `?`) |
|
|
3480
|
+
| `sometimes` | Field is optional, even combined with `required` |
|
|
3481
|
+
| `nullable` | Adds `\| null` to the field's type |
|
|
3482
|
+
| `missing` / `prohibited` | Field is **excluded from the interface entirely** — not just marked optional. A nested key is dropped from its parent's shape instead; see [Array & Nested Rules](#array-nested-rules) |
|
|
3054
3483
|
|
|
3055
3484
|
```php
|
|
3056
3485
|
public function rules(): array
|
|
@@ -3068,7 +3497,7 @@ Fields with no `required`/`sometimes` rule at all (e.g. a bare `'published' => [
|
|
|
3068
3497
|
|
|
3069
3498
|
### Array & Nested Rules
|
|
3070
3499
|
|
|
3071
|
-
Dot-notation (`meta.description`) and wildcard (`tags.*`) rule keys describe constraints on **nested values**, not top-level JSON keys you'd set directly
|
|
3500
|
+
Dot-notation (`meta.description`) and wildcard (`tags.*`) rule keys describe constraints on **nested values**, not top-level JSON keys you'd set directly. They compose into their nearest undotted ancestor and are never emitted as their own quoted property — `"order.id"?: string` would suggest you could send a literal `order.id` key, which Laravel's dot-notation validation never means:
|
|
3072
3501
|
|
|
3073
3502
|
```php
|
|
3074
3503
|
class ArrayRulesRequest extends FormRequest
|
|
@@ -3081,6 +3510,11 @@ class ArrayRulesRequest extends FormRequest
|
|
|
3081
3510
|
|
|
3082
3511
|
'selected_ids' => ['required', 'array', 'between:1,5'],
|
|
3083
3512
|
'selected_ids.*' => ['required', 'integer'],
|
|
3513
|
+
|
|
3514
|
+
'order' => ['required', 'array'],
|
|
3515
|
+
'order.id' => ['required', 'uuid'],
|
|
3516
|
+
'order.items' => ['required', 'array'],
|
|
3517
|
+
'order.items.*.product_id' => ['required', 'integer'],
|
|
3084
3518
|
];
|
|
3085
3519
|
}
|
|
3086
3520
|
}
|
|
@@ -3089,13 +3523,58 @@ class ArrayRulesRequest extends FormRequest
|
|
|
3089
3523
|
```typescript
|
|
3090
3524
|
export interface ArrayRulesRequest {
|
|
3091
3525
|
tags?: string[];
|
|
3092
|
-
"tags.*"?: string;
|
|
3093
3526
|
selected_ids: number[];
|
|
3094
|
-
|
|
3527
|
+
/** @format uuid order.id */
|
|
3528
|
+
order: { id: string; items: { product_id: number }[] };
|
|
3095
3529
|
}
|
|
3096
3530
|
```
|
|
3097
3531
|
|
|
3098
|
-
|
|
3532
|
+
Nesting is unbounded — `order.items.*.product_id` composes through every one of its segments the same way `tags.*` composes through its one. The parent's own presence and nullability rules decide the parent's `?` and `| null` (`selected_ids` is required because its own rule says `required`), while each nested key's own rules decide its optionality inside the composed shape.
|
|
3533
|
+
|
|
3534
|
+
#### Nested edge cases
|
|
3535
|
+
|
|
3536
|
+
| Rules | Generated type | Why |
|
|
3537
|
+
| -------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
3538
|
+
| `'choices' => ['nullable','array']`<br>`'choices.*' => ['nullable','string']` | `choices?: (string \| null)[] \| null` | The element's `nullable` folds into the element type; the array's own `nullable` stays on the array. |
|
|
3539
|
+
| `'options' => ['array']`<br>`'options.*' => ['string']`<br>`'options.default' => ['string']` | `options?: { default?: string } & Record<string, string>` | A wildcard beside a named sibling is a map with some pinned keys — emitted as an intersection, which stays valid TypeScript even when the two halves differ. |
|
|
3540
|
+
| `'meta' => ['array']`<br>`'meta.secret' => ['prohibited']` | `meta?: Record<string, never>` | Every named key is prohibited, so no key is allowed — not an empty object you may add keys to. |
|
|
3541
|
+
| `'empties' => ['array']`<br>`'empties.*' => ['prohibited']` | `empties?: never[]` | The element may never appear, so the array may never hold anything. |
|
|
3542
|
+
| `'v1\.0' => ['required','string']` | `"v1.0": string` | An escaped dot is a literal character in the attribute name, so it stays one field — quoted, since `.` isn't a bare identifier. |
|
|
3543
|
+
| `'items' => ['array']`<br>`'items.0.name' => ['required','string']` | `items?: { name: string }[]` | Explicit numeric indices describe a list. `{ "0": … }` is a type no real JSON array is assignable to. |
|
|
3544
|
+
| `'variants.0.name' => [...]`<br>`'variants.1.email' => [...]` | `variants?: ({ name: string } \| { email: string })[]` | Indices with different shapes union, parenthesized so `[]` applies to the whole union rather than the last member. |
|
|
3545
|
+
|
|
3546
|
+
A `prohibited`/`missing` rule on a nested key drops that key from its parent's shape, and drops its own descendants with it: `'order.secret' => ['prohibited']` alongside `'order.secret.token' => ['required','uuid']` leaves nothing of `secret` in `order`.
|
|
3547
|
+
|
|
3548
|
+
#### Key-list rules: known keys without a full shape
|
|
3549
|
+
|
|
3550
|
+
Three validation rules describe an array's keys without declaring a full nested shape for them.
|
|
3551
|
+
Each declared key becomes a synthesized `unknown`-typed property instead of the array collapsing
|
|
3552
|
+
to `unknown[]` — this is the fix for a `config` field that used to come out `unknown[]` even though
|
|
3553
|
+
`in_array_keys:timezone` tells you exactly which key to expect. The rules differ in whether Laravel's
|
|
3554
|
+
validator actually guarantees the key is present, and the emitted `?` follows that:
|
|
3555
|
+
|
|
3556
|
+
| Rule | Meaning | PHP | TypeScript |
|
|
3557
|
+
| ------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------- |
|
|
3558
|
+
| `required_array_keys:a,b` | all listed keys must be present | `'permissions' => ['required','array','required_array_keys:read,write']` | `permissions: { read: unknown; write: unknown };` |
|
|
3559
|
+
| `in_array_keys:a,b` | at least one listed key must be present — no single key is guaranteed | `'config' => ['required','array','in_array_keys:timezone']` | `config: { timezone?: unknown };` |
|
|
3560
|
+
| `array:a,b` | restricts which keys are allowed; says nothing about presence | `'preferences' => ['nullable','array:theme,locale']` | `preferences?: { theme?: unknown; locale?: unknown } \| null;` |
|
|
3561
|
+
|
|
3562
|
+
A field can combine a key-list rule with a real declared child, and the two merge instead of the
|
|
3563
|
+
synthesized keys being dropped. A real child wins the type and optionality on a name collision;
|
|
3564
|
+
any key with no real child stays synthesized:
|
|
3565
|
+
|
|
3566
|
+
```php
|
|
3567
|
+
'shipping' => ['required', 'array', 'required_array_keys:method,address'],
|
|
3568
|
+
'shipping.method' => ['nullable', 'in:standard,express'],
|
|
3569
|
+
```
|
|
3570
|
+
|
|
3571
|
+
```typescript
|
|
3572
|
+
shipping: { method?: 'standard' | 'express' | null; address: unknown };
|
|
3573
|
+
```
|
|
3574
|
+
|
|
3575
|
+
`method` keeps its own declared type and optionality from `'shipping.method'` even though
|
|
3576
|
+
`required_array_keys` also named it as required; `address` has no declared rule of its own, so it
|
|
3577
|
+
stays the synthesized `unknown`, required because `required_array_keys` said so.
|
|
3099
3578
|
|
|
3100
3579
|
### JSDoc Metadata Annotations
|
|
3101
3580
|
|
|
@@ -3122,6 +3601,28 @@ Certain rules attach a JSDoc comment above the field instead of (or in addition
|
|
|
3122
3601
|
category_id: number;
|
|
3123
3602
|
```
|
|
3124
3603
|
|
|
3604
|
+
An annotation on a nested rule isn't lost when that rule [composes into its parent](#array-nested-rules) — it's hoisted onto the parent's comment block and suffixed with the full rule key it came from, wildcards included, so you can tell which nested key it describes:
|
|
3605
|
+
|
|
3606
|
+
```php
|
|
3607
|
+
'order.id' => ['required', 'uuid'],
|
|
3608
|
+
'products.*.contact_email' => ['required', 'email'],
|
|
3609
|
+
```
|
|
3610
|
+
|
|
3611
|
+
```typescript
|
|
3612
|
+
/** @format uuid order.id */
|
|
3613
|
+
order: {
|
|
3614
|
+
id: string; /* … */
|
|
3615
|
+
}
|
|
3616
|
+
|
|
3617
|
+
/** @format email products.*.contact_email */
|
|
3618
|
+
products: {
|
|
3619
|
+
contact_email: string; /* … */
|
|
3620
|
+
}
|
|
3621
|
+
[];
|
|
3622
|
+
```
|
|
3623
|
+
|
|
3624
|
+
The one exception is a `prohibited` nested key: since it and its descendants are dropped from the type, their annotations are dropped too.
|
|
3625
|
+
|
|
3125
3626
|
### `#[TsCasts]` — Overriding Field Types
|
|
3126
3627
|
|
|
3127
3628
|
Same attribute (and array shape) used by [models](./models.md#tscasts) and resources — place it on the `FormRequest` class to override a field's inferred type, mark it optional, or add a field with a custom imported type:
|
|
@@ -3159,6 +3660,8 @@ export interface UpdatePostRequest {
|
|
|
3159
3660
|
|
|
3160
3661
|
`#[TsCasts]` only replaces the field's **type** and **optionality** (via the `optional` key) — it does not clear a `nullable` rule already on that field. If the underlying rule includes `nullable`, the override's type still gets `| null` appended, same as in the [Anatomy](#anatomy-of-a-generated-form-request) example above.
|
|
3161
3662
|
|
|
3663
|
+
`#[TsCasts]` keys match **generated field names**, and a dot-notation rule key never becomes one — it [composes into its parent](#array-nested-rules). A key like `'order.id'` or `'tags.*'` matches nothing and is silently ignored; it does not add a field either. Override the parent (`'order'`, `'tags'`) to replace the whole shape, or make the rule itself precise enough not to need an override. The only dotted key that matches is one whose dot was escaped in the rule (`'v1\.0'` generates the field `"v1.0"`, so `'v1.0'` overrides it).
|
|
3664
|
+
|
|
3162
3665
|
### `#[TsExtends]`
|
|
3163
3666
|
|
|
3164
3667
|
`FormRequest` classes support `#[TsExtends]` and the `ts_extends.form_requests` config array, the same generic interface-extension mechanism used everywhere else in this package. See [Extending Interfaces](./extending-interfaces.md) for the full attribute reference and config syntax.
|
|
@@ -3700,7 +4203,7 @@ public function boot(): void
|
|
|
3700
4203
|
| ------------------------------------------------- | ---------- |
|
|
3701
4204
|
| `php artisan ts:publish` (full publish) | Yes |
|
|
3702
4205
|
| `php artisan ts:publish --source=App\Models\User` | Yes |
|
|
3703
|
-
| `php artisan ts:publish --preview`
|
|
4206
|
+
| `php artisan ts:publish --preview=true` | Yes |
|
|
3704
4207
|
| Automatic post-migration republish | Yes |
|
|
3705
4208
|
|
|
3706
4209
|
There's no way to distinguish which invocation triggered the hook from inside the closure itself — if you need different behavior for `--source` reruns (for example, skipping expensive filesystem scans that the [Vite plugin](./vite-plugin.md) triggers on every file save), check for cheaper conditions inside the closure (e.g. caching the scan result, or reading an environment variable) rather than relying on the command's own options.
|
|
@@ -3840,7 +4343,7 @@ As with [enums](./enums.md), this package is not meant to be used standalone —
|
|
|
3840
4343
|
If an invokable controller has _additional_ public actions besides `__invoke`, those are attached to the default export via `Object.assign` so you can still call them as properties (`InvokableModelBoundPlusController.extra(...)`).
|
|
3841
4344
|
|
|
3842
4345
|
- Multiple Laravel routes that map to the **same controller method** are de-duplicated into a single export — if one of them is named, the named route wins.
|
|
3843
|
-
- `
|
|
4346
|
+
- Every `GET` route also carries `HEAD` in `methods` (Laravel registers `HEAD` implicitly for every `GET` route), so `.head(...)` and `.form.head(...)` are generated alongside `.get(...)` and `.form.get(...)`.
|
|
3844
4347
|
- A method decorated with `#[TsExclude]` (or a controller class decorated with it) is skipped entirely — see [Filtering & Excluding Routes](#filtering--excluding-routes).
|
|
3845
4348
|
|
|
3846
4349
|
### Anatomy of `defineRoute`
|
|
@@ -3852,7 +4355,7 @@ export const show = defineRoute({
|
|
|
3852
4355
|
name: "posts.show", // Laravel route name, or omitted if unnamed
|
|
3853
4356
|
url: "/posts/{post}", // URI template (or `{domain}{uri}` for domain routes)
|
|
3854
4357
|
domain: "api.example.com", // only present for domain-restricted routes
|
|
3855
|
-
methods: ["get"] as const,
|
|
4358
|
+
methods: ["get", "head"] as const,
|
|
3856
4359
|
args: [{ name: "post", required: true, _routeKey: "id" }] as const,
|
|
3857
4360
|
component: "PostShow", // only present for Inertia routes, see below
|
|
3858
4361
|
});
|
|
@@ -3952,7 +4455,7 @@ Parameters from `{param?}` segments are marked `required: false` and become opti
|
|
|
3952
4455
|
```typescript
|
|
3953
4456
|
export const show = defineRoute({
|
|
3954
4457
|
url: "/optional/{param?}",
|
|
3955
|
-
methods: ["get"] as const,
|
|
4458
|
+
methods: ["get", "head"] as const,
|
|
3956
4459
|
args: [{ name: "param", required: false }] as const,
|
|
3957
4460
|
});
|
|
3958
4461
|
|
|
@@ -3976,7 +4479,7 @@ Domain-restricted routes include a `domain` field, and their compiled URL is pro
|
|
|
3976
4479
|
export const index = defineRoute({
|
|
3977
4480
|
url: "api.example.com/domain",
|
|
3978
4481
|
domain: "api.example.com",
|
|
3979
|
-
methods: ["get"] as const,
|
|
4482
|
+
methods: ["get", "head"] as const,
|
|
3980
4483
|
});
|
|
3981
4484
|
|
|
3982
4485
|
DomainController.index(); // '//api.example.com/domain'
|
|
@@ -4035,7 +4538,7 @@ PostController.destroy.form({ post: 42 });
|
|
|
4035
4538
|
// { action: '/posts/42?_method=DELETE', method: 'post' } — primary method (DELETE) spoofed automatically
|
|
4036
4539
|
```
|
|
4037
4540
|
|
|
4038
|
-
Per-verb form methods (`.form.put(...)`, `.form.patch(...)`, `.form.delete(...)`, `.form.get(...)`) are only needed when a route supports multiple verbs and you want to submit as one that isn't the primary one:
|
|
4541
|
+
Per-verb form methods (`.form.put(...)`, `.form.patch(...)`, `.form.delete(...)`, `.form.get(...)`, `.form.head(...)`) are only needed when a route supports multiple verbs and you want to submit as one that isn't the primary one:
|
|
4039
4542
|
|
|
4040
4543
|
```typescript
|
|
4041
4544
|
// A route registered for both PUT and PATCH — primary is 'put'
|
|
@@ -4043,7 +4546,7 @@ PostController.update.form(); // spoofs _method=PUT (primary)
|
|
|
4043
4546
|
PostController.update.form.patch({ post: 42 }); // explicitly spoofs _method=PATCH instead
|
|
4044
4547
|
```
|
|
4045
4548
|
|
|
4046
|
-
`GET`/`POST` routes never get a spoof added, since HTML forms natively support both.
|
|
4549
|
+
`GET`/`POST` routes never get a spoof added, since HTML forms natively support both. `HEAD` submits as a `'get'` form action with `_method=HEAD` injected, since HTML forms can't submit `HEAD` directly.
|
|
4047
4550
|
|
|
4048
4551
|
### Inertia Integration
|
|
4049
4552
|
|
|
@@ -4056,7 +4559,7 @@ export const post = annotatePageProps<PostPageProps>()(
|
|
|
4056
4559
|
defineRoute({
|
|
4057
4560
|
name: "inertia.post",
|
|
4058
4561
|
url: "/inertia/post/{post}",
|
|
4059
|
-
methods: ["get"] as const,
|
|
4562
|
+
methods: ["get", "head"] as const,
|
|
4060
4563
|
args: [{ name: "post", required: true, _routeKey: "id" }] as const,
|
|
4061
4564
|
component: "PostShow",
|
|
4062
4565
|
}),
|
|
@@ -4089,7 +4592,7 @@ export const conditional = annotatePageProps<
|
|
|
4089
4592
|
>()(
|
|
4090
4593
|
defineRoute({
|
|
4091
4594
|
url: "/inertia/conditional",
|
|
4092
|
-
methods: ["get"] as const,
|
|
4595
|
+
methods: ["get", "head"] as const,
|
|
4093
4596
|
component: {
|
|
4094
4597
|
authenticated: "Conditional/Authenticated",
|
|
4095
4598
|
guest: "Conditional/Guest",
|
|
@@ -4826,21 +5329,22 @@ A complete reference of every option in `config/ts-publish.php`, grouped by feat
|
|
|
4826
5329
|
|
|
4827
5330
|
### Models (`models.*`)
|
|
4828
5331
|
|
|
4829
|
-
| Config Key | Type | Default | Description
|
|
4830
|
-
| --------------------------------- | -------- | --------------------------------- |
|
|
4831
|
-
| `models.enabled` | `bool` | `true` | Enable or disable model publishing
|
|
4832
|
-
| `models.namespace` | `string` | `'models'` | Namespace label used in the global declaration file
|
|
4833
|
-
| `models.relationship_case` | `string` | `'snake'` | Case style for relationships: `snake`, `camel`, or `pascal`
|
|
4834
|
-
| `models.nullable_relations` | `bool` | `true` | Append `\| null` to singular relation types based on smart detection
|
|
4835
|
-
| `models.
|
|
4836
|
-
| `models.
|
|
4837
|
-
| `models.
|
|
4838
|
-
| `models.
|
|
4839
|
-
| `models.
|
|
4840
|
-
| `models.
|
|
4841
|
-
| `models.
|
|
4842
|
-
| `models.
|
|
4843
|
-
| `models.
|
|
5332
|
+
| Config Key | Type | Default | Description |
|
|
5333
|
+
| --------------------------------- | -------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
5334
|
+
| `models.enabled` | `bool` | `true` | Enable or disable model publishing |
|
|
5335
|
+
| `models.namespace` | `string` | `'models'` | Namespace label used in the global declaration file |
|
|
5336
|
+
| `models.relationship_case` | `string` | `'snake'` | Case style for relationships: `snake`, `camel`, or `pascal` |
|
|
5337
|
+
| `models.nullable_relations` | `bool` | `true` | Append `\| null` to singular relation types based on smart detection |
|
|
5338
|
+
| `models.exclude_hidden` | `bool` | `false` | Omit Eloquent `$hidden` attributes — from model interfaces always, and from resource property sets wherever they're derived implicitly (see [API Resources § `exclude_hidden` and attribute filters](./api-resources.md#exclude-hidden-and-attribute-filters)) |
|
|
5339
|
+
| `models.relation_nullability_map` | `array` | `[]` | Override nullability strategy per relation type |
|
|
5340
|
+
| `models.template` | `string` | `laravel-ts-publish::model-split` | Blade template for model TypeScript output |
|
|
5341
|
+
| `models.included` | `array` | `[]` | Only publish these models (empty = all) |
|
|
5342
|
+
| `models.excluded` | `array` | `[]` | Exclude these models from publishing |
|
|
5343
|
+
| `models.additional_directories` | `array` | `[]` | Extra directories to search for models |
|
|
5344
|
+
| `models.collector_class` | `string` | `ModelsCollector` | Discovers PHP model classes |
|
|
5345
|
+
| `models.generator_class` | `string` | `ModelGenerator` | Orchestrates transforming and writing |
|
|
5346
|
+
| `models.transformer_class` | `string` | `ModelTransformer` | Converts PHP class into TypeScript data |
|
|
5347
|
+
| `models.writer_class` | `string` | `ModelWriter` | Writes TypeScript model files |
|
|
4844
5348
|
|
|
4845
5349
|
### Enums (`enums.*`)
|
|
4846
5350
|
|
package/dist/enums.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AsEnum, CaseValue, DefineEnumResult, EnumConst, FromResult } from '
|
|
1
|
+
import { AsEnum, CaseValue, DefineEnumResult, EnumConst, FromResult } from '@tolki/types';
|
|
2
2
|
export type { AsEnum, CaseValue, DefineEnumResult, EnumConst, FromResult };
|
|
3
3
|
/**
|
|
4
4
|
* Creates an enum instance from a case value similar to PHP's `BackedEnum::from()`
|
package/dist/routes.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DefineRouteResult, InferPageProps, InferRequestPayload, RouteArgMeta, RouteCallResult, RouteCallResultWithComponent, RouteComponentType, RouteFormResult, RouteMetadata, RouteQueryOptions } from '
|
|
1
|
+
import { DefineRouteResult, InferPageProps, InferRequestPayload, RouteArgMeta, RouteCallResult, RouteCallResultWithComponent, RouteComponentType, RouteFormResult, RouteMetadata, RouteQueryOptions } from '@tolki/types';
|
|
2
2
|
export type { DefineRouteResult, InferPageProps, InferRequestPayload, RouteArgMeta, RouteCallResult, RouteCallResultWithComponent, RouteComponentType, RouteFormResult, RouteMetadata, RouteQueryOptions, };
|
|
3
3
|
/**
|
|
4
4
|
* Attach a phantom page props type to a `defineRoute` result without losing
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tolki/ts",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "A set of TypeScript utilities for the Laravel TypeScript Publish PHP package.",
|
|
5
5
|
"author": "Abraham Arango <https://github.com/abetwothree>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -39,8 +39,8 @@
|
|
|
39
39
|
"tolki"
|
|
40
40
|
],
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@tolki/types": "^1.
|
|
43
|
-
"@tolki/utils": "^1.0
|
|
42
|
+
"@tolki/types": "^1.5.0",
|
|
43
|
+
"@tolki/utils": "^1.2.0"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
46
|
"vite": "^7.0.0||^8.0.0"
|