@tolki/ts 1.0.4 → 1.1.0

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 CHANGED
@@ -412,6 +412,8 @@ let user: app.models.User;
412
412
  let status: app.enums.StatusType;
413
413
  ```
414
414
 
415
+ Unlike in [the enum's own file](https://tolki.abe.dev/ts/enums.html#value-key-types), an enum's name in this file, such as `app.enums.Status`, is an interface of its cases, so type an enum value as `app.enums.StatusType`.
416
+
415
417
  A namespace segment of more than one word is camel-cased, because a hyphen isn't valid in a namespace name. `App\Http\Resources\ReportCards\SummaryCardResource` is `app.http.resources.reportCards.SummaryCardResource`, while its file is written under `report-cards/`. An acronym is lowered as one word, so `API` is `api` and `HTTPClient` is `httpClient`.
416
418
 
417
419
  When two published types share a name, such as `App\Models\User` and `Crm\Models\User`, each reference from another namespace is qualified with the namespace of the class your PHP code names, such as `crm.models.User`.
@@ -560,6 +562,8 @@ export const Color = defineEnum({
560
562
 
561
563
  export type ColorType = "red" | "green" | "blue";
562
564
  export type ColorKind = "Red" | "Green" | "Blue";
565
+
566
+ export type Color = ColorType;
563
567
  ```
564
568
 
565
569
  Each part of the file does one job:
@@ -568,7 +572,7 @@ Each part of the file does one job:
568
572
  - **`backed`**: whether the PHP enum is backed. [`EnumResource`](https://tolki.abe.dev/ts/enum-api-resource.html) responses include the same key, and [`AsEnum`](#type-reference) types it.
569
573
  - **`hex`**: an instance method published with [`#[TsEnumMethod]`](#tsenummethod), with one value per case.
570
574
  - **`_cases`, `_methods` and `_static`**: the lists the `@tolki/ts` functions read to build a PHP-like instance. See [Runtime Utilities](#runtime-utilities).
571
- - **`ColorType` and `ColorKind`**: type aliases for the case values and the case names. See [Value & Key Types](#value--key-types).
575
+ - **`ColorType`, `ColorKind` and `Color`**: type aliases for the case values and the case names. The `Color` type is another name for `ColorType`, so `Color` is both the enum object and the type of its values. See [Value & Key Types](#value--key-types).
572
576
 
573
577
  ### Enum Attributes
574
578
 
@@ -630,6 +634,8 @@ The attribute takes these parameters:
630
634
  | `description` | `string` | `''` | A JSDoc comment above the property. |
631
635
  | `params` | `array` | `[]` | Named arguments to call the method with. See [Methods With Required Parameters](#methods-with-required-parameters). |
632
636
 
637
+ The method must be public. A private or protected method with the attribute isn't published, and `ts:publish` warns about it.
638
+
633
639
  ##### Methods With Required Parameters
634
640
 
635
641
  A method with required parameters is skipped by default, instead of publishing misleading `null` values. To include one, pass `params`. The package calls the method once per case, with those values as named arguments:
@@ -692,7 +698,7 @@ export const Status = defineEnum({
692
698
  } as const);
693
699
  ```
694
700
 
695
- A static method with required parameters is skipped unless you pass `params`, the same as with `#[TsEnumMethod]`.
701
+ The same rules apply as with `#[TsEnumMethod]`: the method must be public, and a method with required parameters is skipped unless you pass `params`.
696
702
 
697
703
  #### `#[TsEnum]`
698
704
 
@@ -721,6 +727,8 @@ export const UserStatus = defineEnum({
721
727
 
722
728
  export type UserStatusType = "active" | "inactive";
723
729
  export type UserStatusKind = "Active" | "Inactive";
730
+
731
+ export type UserStatus = UserStatusType;
724
732
  ```
725
733
 
726
734
  The file takes the new name too (`user-status.ts`), and models that use the enum refer to it as `UserStatusType`. The attribute takes these parameters:
@@ -730,7 +738,7 @@ The file takes the new name too (`user-status.ts`), and models that use the enum
730
738
  | `name` | `string` | The TypeScript const name. Use it when two enums in one namespace publish the same name, or when a [route file](https://tolki.abe.dev/ts/routing.html#what-the-props-expression-can-be) uses two same-named enums from different namespaces. |
731
739
  | `description` | `string` | A JSDoc comment. It takes priority over any PHPDoc description. |
732
740
 
733
- An enum `Role` publishes the type `RoleType`. A second enum named `RoleType` in the same namespace publishes a const with that name, and the two can't share a barrel file or a global namespace. `ts:publish` warns when it finds such a pair. Rename one of them with `#[TsEnum]`. In two different namespaces this pair is fine, because a file that imports both gets an alias for one.
741
+ When two classes in one namespace publish the same name, their barrel file and the global declaration file can't export both. For example, an enum `Role` publishes the type `RoleType`, so a second enum named `RoleType` in the same namespace clashes with it. `ts:publish` warns about any such pair, whether the classes are enums, models, resources, form requests, broadcast events or [composed types](https://tolki.abe.dev/ts/custom-types.html#composed-types). Move one of them to a namespace of its own, or rename it. An enum takes a new name with `#[TsEnum]`. In two different namespaces the pair is fine, because a file that imports both gets an alias for one. Two kinds of class in one directory, such as an enum `App\Models\Status` beside the models, drop each other's barrel exports, so keep each kind of class in a namespace of its own.
734
742
 
735
743
  #### `#[TsCase]`
736
744
 
@@ -761,8 +769,12 @@ export const Status = defineEnum({
761
769
 
762
770
  export type StatusType = "enabled" | "disabled";
763
771
  export type StatusKind = "Enabled" | "Disabled";
772
+
773
+ export type Status = StatusType;
764
774
  ```
765
775
 
776
+ A published [instance method](#tsenummethod) keys its values by the new case names too. `Status.from("enabled")` resolves each method to its value for `Status::Active`, and [`EnumResource`](https://tolki.abe.dev/ts/enum-api-resource.html) sends the same values.
777
+
766
778
  The attribute takes these parameters:
767
779
 
768
780
  | Parameter | Type | Description |
@@ -782,6 +794,8 @@ export type StatusType = "active" | "inactive";
782
794
  export type StatusKind = "Active" | "Inactive"; // backed enums only
783
795
  ```
784
796
 
797
+ An enum with no cases publishes `never` for each alias.
798
+
785
799
  Use the aliases to type a raw value or a case name:
786
800
 
787
801
  ```typescript
@@ -791,9 +805,23 @@ function setStatus(status: StatusType) {} // only 'active' | 'inactive'
791
805
  function setStatusByKey(status: StatusKind) {} // only 'Active' | 'Inactive'
792
806
  ```
793
807
 
808
+ The enum's own name is also a type, an alias of its `{Name}Type`, so for a unit enum it's the union of its case names. One import gives you the enum object and the type of its values, as a native TypeScript `enum` does:
809
+
810
+ ```typescript
811
+ import { Color } from "@js/types/data/app/enums";
812
+
813
+ let color: Color = Color.Red; // only 'red' | 'green' | 'blue'
814
+
815
+ Color.from(color).hex; // '#EF4444'
816
+ ```
817
+
818
+ Use `import type { Color }` when you need only the type. Every enum file has this alias, with or without metadata and the `defineEnum()` wrapper.
819
+
820
+ To list the values or the names at runtime, call [`values`](#values) or [`keys`](#keys).
821
+
794
822
  #### Reading `->value` and `->name`
795
823
 
796
- Read an enum's `->value` or `->name` in an API resource, an Inertia page prop, a broadcast event, or anything else the package types, and the property publishes the enum's alias. The file imports the alias for you. Here a `PostSummaryResource` reads a `Post` model that casts `status` to the int-backed `PostStatus` enum and `visibility` to the unit enum `Visibility`:
824
+ Read an enum's `->value` or `->name` in an API resource, an Inertia page prop, a broadcast event, or anything else the package types, and the property publishes the enum's alias, or the case's own value when you name the case. The file imports the alias for you. Here a `PostSummaryResource` reads a `Post` model that casts `status` to the int-backed `PostStatus` enum and `visibility` to the unit enum `Visibility`:
797
825
 
798
826
  ```php
799
827
  enum PostStatus: int
@@ -814,7 +842,7 @@ public function toArray(Request $request): array
814
842
  }
815
843
  ```
816
844
 
817
- Each property publishes the alias that lists what PHP sends for it:
845
+ Each property publishes what PHP can send for it:
818
846
 
819
847
  ```typescript
820
848
  import type {
@@ -827,22 +855,39 @@ export interface PostSummaryResource {
827
855
  status: PostStatusType;
828
856
  status_name: PostStatusKind;
829
857
  visibility: VisibilityType;
830
- published: PostStatusType;
858
+ published: 1;
831
859
  }
832
860
  ```
833
861
 
834
862
  A backed enum's `->value` publishes its `{Name}Type`, and its `->name` publishes its `{Name}Kind`. A unit enum's `->name` publishes its `{Name}Type`, because its values are its case names.
835
863
 
836
- `PostStatus::Published->value` and `PostStatus::from($value)->value` publish `PostStatusType` too. After `PostStatus::tryFrom()`, `?->value` publishes `PostStatusType | null`. A method you call on a case publishes its return type.
864
+ A case you write out can send only its own value, so it publishes that value: `PostStatus::Published->value` publishes `1`, and `PostStatus::Published->name` publishes `'Published'`. A ternary between two cases publishes both values. `PostStatus::from($value)->value` publishes `PostStatusType`, and after `PostStatus::tryFrom()`, `?->value` publishes `PostStatusType | null`. A method you call on a case publishes its return type.
865
+
866
+ In an API resource, `PostStatus::cases()` publishes a list of the alias. A map over the cases publishes what its callback reads from each case, with or without a type hint:
867
+
868
+ ```php
869
+ 'statuses' => PostStatus::cases(),
870
+ 'values' => array_map(fn ($case) => $case->value, PostStatus::cases()),
871
+ 'names' => collect(PostStatus::cases())
872
+ ->map(fn (PostStatus $case) => $case->name)
873
+ ->all(),
874
+ ```
875
+
876
+ Each key publishes a list:
877
+
878
+ ```typescript
879
+ statuses: PostStatusType[];
880
+ values: PostStatusType[];
881
+ names: PostStatusKind[];
882
+ ```
883
+
884
+ `array_column(PostStatus::cases(), 'value')` publishes `unknown`, so map the cases instead.
837
885
 
838
886
  The property uses the alias only when `ts:publish` publishes the enum, and when no case's `#[TsCase]` changes what the alias lists. For a `{Name}Type` that's the case's `value`, and for a `{Name}Kind` its `name`. Otherwise the property publishes the literal union of what PHP sends.
839
887
 
840
888
  An enum the [filters](#filtering--excluding-enums) leave out publishes the literal union too, and so does every enum while `enums.enabled` is off. For the `Status` enum in the [`#[TsCase]`](#tscase) example, `->value` publishes `1 | 0` and `->name` publishes `'Active' | 'Inactive'`. An int-backed enum with a case outside JavaScript's safe integer range (±2⁵³−1) publishes `number` for `->value`.
841
889
 
842
- In two cases the alias can't be imported, so the property publishes the literal union:
843
-
844
- - A helper method's array that a resource uses as a value. A spread of the same helper keeps the aliases, as [Methods Declared as a Bare `array`](https://tolki.abe.dev/ts/api-resources.html#methods-declared-as-a-bare-array) shows.
845
- - A [route file](https://tolki.abe.dev/ts/routing.html), the [Inertia shared data](https://tolki.abe.dev/ts/inertia.html) file or a [model metadata](https://tolki.abe.dev/ts/model-metadata.html) companion that reads the `->name` of two enums with the same class name, such as `App\Enums\Status` and `App\Crm\Enums\Status`. These files can't import two names that clash, so each read publishes its case names.
890
+ As in a resource, two enums with the same class name, such as `App\Enums\Status` and `App\Crm\Enums\Status`, are imported under aliases in a [route file](https://tolki.abe.dev/ts/routing.html), the [Inertia shared data](https://tolki.abe.dev/ts/inertia.html) file and a [model metadata](https://tolki.abe.dev/ts/model-metadata.html) companion, as in `StatusKind as CrmStatusKind`.
846
891
 
847
892
  ### Metadata & the `defineEnum()` Wrapper
848
893
 
@@ -855,7 +900,7 @@ const instance = Status.from("active");
855
900
  // { name: 'Active', value: 'active', backed: true, label: 'Active User', options: [...] }
856
901
  ```
857
902
 
858
- An instance method resolves to its value for the matched case (`label`), and a static method passes through as it is (`options`). See [Runtime Utilities](#runtime-utilities) for every function.
903
+ An instance method resolves to its value for the matched case (`label`), and a static method passes through as it is (`options`). See [Runtime Utilities](#runtime-utilities) for every function. [`values`](#values) and [`keys`](#keys) read `_cases` too.
859
904
 
860
905
  #### Disabling Metadata or the `@tolki/ts` Wrapper
861
906
 
@@ -935,9 +980,9 @@ Enums use the same include and exclude settings as models, resources and the oth
935
980
 
936
981
  ### Runtime Utilities
937
982
 
938
- `@tolki/ts` exports these functions, which give `defineEnum()` its PHP-like behavior. You normally call them through the published enum (`Status.from(...)`) instead of importing them.
983
+ `@tolki/ts` exports these functions. `from`, `tryFrom` and `cases` give `defineEnum()` its PHP-like behavior, and you normally call them through the published enum (`Status.from(...)`). `values` and `keys` aren't bound to the enum, so you import them.
939
984
 
940
- [cases](#cases) [defineEnum](#defineenum) [from](#from) [tryFrom](#tryfrom)
985
+ [cases](#cases) [defineEnum](#defineenum) [from](#from) [keys](#keys) [tryFrom](#tryfrom) [values](#values)
941
986
 
942
987
  #### `cases`
943
988
 
@@ -982,6 +1027,19 @@ const result = from(Status, "active");
982
1027
  from(Status, "non-valid-key"); // throws
983
1028
  ```
984
1029
 
1030
+ #### `keys`
1031
+
1032
+ Like `array_column(Color::cases(), 'name')` in PHP, `keys` returns the enum's case names in case order, typed as a union of those names:
1033
+
1034
+ ```typescript
1035
+ import { keys } from "@tolki/ts";
1036
+ import { Color } from "@js/types/data/app/enums";
1037
+
1038
+ keys(Color); // ['Red', 'Green', 'Blue']
1039
+ ```
1040
+
1041
+ Like `values`, `keys` reads the `_cases` list and returns an empty array without `enums.metadata_enabled`.
1042
+
985
1043
  #### `tryFrom`
986
1044
 
987
1045
  Like PHP's [tryFrom](https://www.php.net/manual/en/backedenum.tryfrom.php), `tryFrom` works like `from` but returns `null` for a value that matches no case:
@@ -994,6 +1052,21 @@ const result = tryFrom(Status, "active");
994
1052
  const missing = tryFrom(Status, "non-valid-key"); // null
995
1053
  ```
996
1054
 
1055
+ #### `values`
1056
+
1057
+ Like `array_column(Color::cases(), 'value')` in PHP, `values` returns the enum's case values in case order, typed as its `{Name}Type` union:
1058
+
1059
+ ```typescript
1060
+ import { values } from "@tolki/ts";
1061
+ import { Color } from "@js/types/data/app/enums";
1062
+
1063
+ values(Color); // ['red', 'green', 'blue']
1064
+ ```
1065
+
1066
+ A unit enum publishes each case name as its value, so `values` returns its case names. PHP's `array_column()` returns an empty array for a unit enum.
1067
+
1068
+ `values` and `keys` read the `_cases` list, so they need `enums.metadata_enabled` and return an empty array without it. `defineEnum()` doesn't add `values` or `keys` to the enum. An enum that publishes its own `values()` or `keys()` static method keeps that published value under the name, so `Status.values` is the static method's published output while `values(Status)` returns the case values.
1069
+
997
1070
  ### Vite Plugin
998
1071
 
999
1072
  The `@tolki/ts` package ships a Vite plugin that republishes enums and routes automatically during development. See the [Vite Plugin documentation](https://tolki.abe.dev/ts/vite-plugin.html).
@@ -1010,6 +1083,7 @@ The runtime functions come from `@tolki/ts`. The types come from `@tolki/types`,
1010
1083
  | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1011
1084
  | `defineEnum()` | Wraps a raw enum const with bound `from`, `tryFrom` and `cases` helpers. |
1012
1085
  | `from()`, `tryFrom()`, `cases()` | Standalone versions that take the enum object as their first argument. |
1086
+ | `values()`, `keys()` | The case values, or the case names, in case order. |
1013
1087
  | `EnumConst` | The base shape every generated enum const satisfies. |
1014
1088
  | `CaseKeys<T>` / `CaseValue<T>` | The union of case key names, or of case values, for an enum const. |
1015
1089
  | `MethodKeys<T>` / `StaticKeys<T>` | The union of instance method key names, or of static method key names. |
@@ -1387,7 +1461,7 @@ Most columns and accessors type themselves. When one publishes `unknown` or `unk
1387
1461
  2. A class-level `@property` or `@property-read` tag, including one that uses a `@phpstan-type` or `@phpstan-import-type` alias.
1388
1462
  3. A `@return MorphTo<A|B, $this>` generic on a `morphTo()` relation.
1389
1463
 
1390
- PHPStan and Larastan read all of them, so the annotation that fixes your TypeScript is also checked by static analysis, and the package reads them with no configuration. `#[TsCasts]` is still the right tool when a shape's keys are built at runtime, or when the type belongs to the frontend and needs its own import. The [Annotation Checklist](#annotation-checklist) lists each case by symptom.
1464
+ PHPStan and Larastan read all of them, so the annotation that fixes your TypeScript is also checked by static analysis, and the package reads them with no configuration. When a docblock has more than one tag of a kind, the package reads them in PHPStan's order: `@phpstan-return`, then `@psalm-return`, then `@return`, and the same for `@var`, `@param`, `@property` and `@use`. A prefixed tag that's vague, such as `@phpstan-return array<string, mixed>`, yields to a precise plain tag. `#[TsCasts]` is still the right tool when a shape's keys are built at runtime, or when the type belongs to the frontend and needs its own import. The [Annotation Checklist](#annotation-checklist) lists each case by symptom.
1391
1465
 
1392
1466
  #### Accessor Getter Bodies
1393
1467
 
@@ -1427,7 +1501,7 @@ export interface ReleaseMutators {
1427
1501
  }
1428
1502
  ```
1429
1503
 
1430
- The package reads `Attribute::make()`, `Attribute::get()`, `new Attribute(get: ...)` and old-style `get{Name}Attribute()` bodies. An accessor declared in a trait is read against the model that uses the trait. A method the getter calls is read the same way: `channelOptions()` returns `static::channelLabels()`, whose signature is a bare `: array`, and still publishes `{ "1": string; "2": string }`. A getter that returns an untyped property is typed from the property's default value, so `channels()`, which returns `protected $allowedChannels`, publishes `string[]`.
1504
+ The package reads `Attribute::make()`, `Attribute::get()`, `new Attribute(get: ...)` and old-style `get{Name}Attribute()` bodies. An accessor declared in a trait is read against the model that uses the trait. A method the getter calls is read the same way: `channelOptions()` returns `static::channelLabels()`, whose signature is a bare `: array`, and still publishes `{ "1": string; "2": string }`. A getter that returns an untyped property is typed from the property's default joined with what the class and its children write to it, so `channels()`, which returns `protected $allowedChannels`, publishes `string[]` when nothing writes it.
1431
1505
 
1432
1506
  A specific return type or `Attribute<Get, Set>` generic is always read first, so the getter body never overrides an accurate annotation. When the getter can't be typed, the accessor keeps the type from its signature or docblock, or publishes `unknown` if it has neither. That happens when the getter:
1433
1507
 
@@ -1441,9 +1515,15 @@ A specific return type or `Attribute<Get, Set>` generic is always read first, so
1441
1515
 
1442
1516
  The `null` case keeps a getter from publishing a type that's plainly wrong: `fn ($value, array $attributes) => $attributes['title'] ?? null` publishes `unknown`, not `null`, because its real value is the title.
1443
1517
 
1518
+ A getter closure with no native return type takes its type from a `@return` docblock written just before it, so `Attribute::get(/** @return int */ fn () => json_decode($this->stats_json))` publishes `number`. The package reads that docblock only when it can't type what the getter returns, and ignores a vague one, such as `@return mixed`.
1519
+
1520
+ A getter that reads an attribute through `getAttribute()` or `getAttributeValue()` with a literal name takes the attribute's type, so `Attribute::get(fn () => $this->getAttribute('title'))` publishes `string`, as `fn () => $this->title` does.
1521
+
1522
+ Laravel runs an accessor's getter for a `NULL` column too, so an accessor on a nullable column publishes `| null` only where its getter can return `null`. A getter whose native return type is non-null, such as `fn (?string $value): array => …`, publishes no `| null`. One whose native return type allows `null`, such as `: ?array`, always publishes it, even when its `Attribute<…>` docblock leaves the `null` out.
1523
+
1444
1524
  #### Typing `array` Casts With `@property`
1445
1525
 
1446
- A column cast to `'array'`, or to any cast with no more specific type, publishes as `unknown[]`. Instead of `#[TsCasts]`, add a class-level `@property` or `@property-read` tag with the real shape. It's the same tag PHPStan and Larastan read:
1526
+ A column cast to `'array'`, or to any cast with no more specific type, publishes as `unknown[]`. Laravel sends the decoded JSON as it is, so a column holding an object, such as `{"theme":"dark"}`, is sent as that object, which `unknown[]` doesn't describe. The same holds for `collection` and `AsCollection` casts. Instead of `#[TsCasts]`, add a class-level `@property` or `@property-read` tag with the real shape. It's the same tag PHPStan and Larastan read:
1447
1527
 
1448
1528
  ```php
1449
1529
  /**
@@ -1463,7 +1543,7 @@ A tag applies only when the column's own type is vague. It never overrides a spe
1463
1543
 
1464
1544
  A tag that is still partly vague is used when it's more specific than the type it replaces. `@property array<string, mixed>|null $settings` turns a plain `'array'` cast into `Record<string, unknown> | null`: the type still names `unknown`, but it beats `unknown[] | null`. A tag that is exactly as vague as the original is ignored: `unknown`, `unknown[]`, `object`, or the `unknown[] | Record<string, unknown>` of a bare collection.
1465
1545
 
1466
- The package also reads `@property` tags on the traits the model and its parents use, and on the traits those traits use. A trait that supplies an accessor can document it that way. The `$`-less form some packages use, `@property string[] labels`, works as long as nothing follows the property name.
1546
+ The package also reads `@property` tags on the traits the model and its parents use, and on the traits those traits use. A trait that supplies an accessor can document it that way. A class a trait's docblocks name resolves through the trait file's imports, not the model's, and so does the `@var` of a property the trait declares. The `$`-less form some packages use, `@property string[] labels`, works as long as nothing follows the property name.
1467
1547
 
1468
1548
  #### Typing JSON Columns With `@phpstan-type` Aliases
1469
1549
 
@@ -1538,16 +1618,18 @@ A docblock intersection resolves each member and joins them with `&`:
1538
1618
  protected function assignedUsers(): Attribute
1539
1619
  ```
1540
1620
 
1541
- `User` keeps its import, but `pivot` publishes as `unknown`:
1621
+ Both classes keep their types, and the file imports both:
1542
1622
 
1543
1623
  ```typescript
1624
+ import type { TaskAssignment, User } from ".";
1625
+
1544
1626
  export interface ProjectMutators {
1545
- assigned_users: (User & { pivot: unknown })[];
1627
+ assigned_users: (User & { pivot: TaskAssignment })[];
1546
1628
  // …
1547
1629
  }
1548
1630
  ```
1549
1631
 
1550
- A class named inside an `object{...}` shape always publishes as `unknown`, which is why `TaskAssignment` is lost here. A member that can't be resolved is dropped from the intersection, instead of turning the whole type into `unknown`, since `A & B` is assignable to `A`.
1632
+ A model or an enum inside a docblock shape keeps its type at any depth, as `TaskAssignment` does here. Two kinds of shape publish each model and enum in them as `unknown`: one that also names another class, such as an API resource, and one that spells a class's name as a string literal or a key, as in `array{kind: 'User', owner: User}`. A member that can't be resolved is dropped from the intersection, instead of turning the whole type into `unknown`, since `A & B` is assignable to `A`.
1551
1633
 
1552
1634
  #### Trait `@template` Bindings
1553
1635
 
@@ -1577,11 +1659,17 @@ export interface ProjectMutators {
1577
1659
  }
1578
1660
  ```
1579
1661
 
1580
- PHPStan reads the `@use` tag for the same purpose, so static analysis checks the binding too.
1662
+ PHPStan reads the `@use` tag for the same purpose, so static analysis checks the binding too. The trait's name in the tag resolves through the file's imports, then the model's namespace, so a trait declared beside the model needs no `use` import.
1581
1663
 
1582
1664
  #### Custom Cast Classes
1583
1665
 
1584
- A custom cast without [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes the return type of its `get()` method. A cast class that implements `SerializesCastableAttributes`, including one a `Castable` value object names, publishes the return type of its `serialize()` method instead, because that's what Laravel sends when it converts the model to JSON.
1666
+ A custom cast without [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes the return type of its `get()` method. When the cast class has a `serialize()` method, including one a `Castable` value object names, Laravel sends what `serialize()` returns when it converts the model to JSON, with or without the `SerializesCastableAttributes` interface. The column then publishes:
1667
+
1668
+ - **No declared type, or `mixed`**: the type its `return` statements prove, so `return (string) $value;` publishes `string`. Where they prove none, the column keeps `get()`'s type, except a `mixed` `serialize()` on a cast that implements the interface, which publishes `unknown | null`.
1669
+ - **A bare `array` or `object`, on a cast without the interface**: `get()`'s type, where `get()` returns a value object or an array shape. `?object` and `array|object` work the same way. Over a scalar `get()`, a bare `array` publishes `unknown[] | Record<string, unknown>`.
1670
+ - **Any other declared type**: that type, such as `string`.
1671
+
1672
+ Laravel calls `get()` for a `NULL` column too, so a nullable column cast to a class whose `get()` declares a non-null return type publishes no `| null`. For a `coordinate_data` column that may be `NULL`, cast with a `get()` that always returns a `Coordinate`, the model publishes `coordinate_data: { lat: number; lng: number }`. Laravel sends a `null` from `get()` without calling `serialize()`, so a `get()` that declares a nullable return type, or returns `null` itself, adds `| null` to the `serialize()` type.
1585
1673
 
1586
1674
  When `get()`'s native type is missing or vague, such as a bare `array`, the `@return` docblock sets the type, so `@return list<LegDto>` publishes a list of `LegDto`'s public properties, the shape `json_encode()` writes. A `@return` that names a model, such as `list<User>`, or another class that doesn't publish as an inline shape keeps `unknown[]`. A `get()` that declares neither publishes `unknown`.
1587
1675
 
@@ -1689,7 +1777,9 @@ final readonly class ShippingOptions implements Arrayable
1689
1777
  }
1690
1778
  ```
1691
1779
 
1692
- An accessor or cast that returns this DTO publishes as `{ carrier: string; insured: boolean; trackingUrl: string | null }`. Nullable properties keep their `| null`. Private, protected and static properties are left out, because `(array) $this` doesn't include them. A property typed as a class or an enum, such as a model, publishes as `unknown`, because the inline shape can't import it. A property whose class has or inherits a [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes that type, with its import.
1780
+ An accessor or cast that returns this DTO publishes as `{ carrier: string; insured: boolean; trackingUrl: string | null }`. Nullable properties keep their `| null`. Private, protected and static properties are left out, because `(array) $this` doesn't include them. A property typed as an enum or a published model publishes that type, and the file imports it, so `public Status $status` publishes `status: StatusType`. A property whose class has or inherits a [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes that type, with its import.
1781
+
1782
+ A promoted property with no `@var` takes its type from the constructor's `@param`, as PHPStan reads it. So a constructor documented `@param list<string> $stops` publishes its promoted `public array $stops` as `stops: string[]` instead of `unknown[]`.
1693
1783
 
1694
1784
  Optional is separate from nullable. A property that is neither promoted nor given a default value publishes as an optional key. Add `public string $summary;` to the class body above, assigned in the constructor, and it publishes as `summary?: string`. PHP leaves an unassigned typed property out of `(array) $this`, and the package can't tell whether the constructor always assigns it. To keep the key required, promote the property, or give it a default value on a DTO that isn't `readonly`. A `@return array{...}` docblock on `toArray()` always wins, so add one when the properties don't tell the whole story.
1695
1785
 
@@ -1855,11 +1945,11 @@ The `unknown[]` collection row is the bare form. `AsEnumCollection::of(...)`, `A
1855
1945
 
1856
1946
  A parameterized docblock generic in `@return`, `@property` or `Attribute<>` publishes a more specific type, based on its key type. Every container behaves the same way for a given key type:
1857
1947
 
1858
- | Key type | Emitted | Containers |
1859
- | -------------------- | -------------------------- | ----------------------------------------------------- |
1860
- | `int`, or omitted | `X[]` | `list<X>`, `array<…>`, `iterable<…>`, `Collection<…>` |
1861
- | `string` | `Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
1862
- | `array-key`, `mixed` | `X[] \| Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
1948
+ | Key type | Emitted | Containers |
1949
+ | ----------------------------------- | -------------------------- | ----------------------------------------------------- |
1950
+ | `int`, or omitted | `X[]` | `list<X>`, `array<…>`, `iterable<…>`, `Collection<…>` |
1951
+ | `string` | `Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
1952
+ | `int\|string`, `array-key`, `mixed` | `X[] \| Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
1863
1953
 
1864
1954
  `list<X>` has no key type, so it always publishes as `X[]`. A container with no generic at all, such as a bare `Collection`, uses the [Arrays & Objects](#arrays--objects) table above instead.
1865
1955
 
@@ -2110,14 +2200,14 @@ Each returned key's TypeScript type comes from the first of these that applies:
2110
2200
  3. **The method body**: the package reads the returned array literal, with `$model` typed as its declared class. These need no annotation:
2111
2201
  - Scalars, casts such as `(string) …`, and nested inline arrays
2112
2202
  - Calls on `$model` whose Laravel signature or docblock declares a return type, such as `getTable()`, `getKeyName()`, `getRouteKeyName()` and `getMorphClass()`, which all publish as `string`
2113
- - Enum values, including a case written inline such as `'status' => Status::Active`, which import their `{Name}Type` alias from the generated enums, the same as a `#[TsCasts]` import would
2203
+ - Enum values, including a case written inline such as `'status' => Status::Active`, which import their `{Name}Type` alias from the generated enums, the same as a `#[TsCasts]` import would. Two enums with the same class name are imported under aliases, such as `StatusType as CrmStatusType`, and so are their `{Name}Kind` aliases
2114
2204
  - An `instanceof` test on `$model`, which narrows it where the test holds, and relation calls that the query answers, as in `$model instanceof Post ? $model->comments()->count() : null`, which publishes `number | null`
2115
2205
 
2116
2206
  When the body's type for a key still contains `unknown`, the package ignores it, and the key needs a docblock or `#[TsCasts]` type. A helper with no declared return type, such as `private function tableFor($model)`, is that case. Inside a ternary or another union, a value the body can't type is left out instead, as in an API resource. See [Values Left Out of a Union](https://tolki.abe.dev/ts/api-resources.html#values-left-out-of-a-union).
2117
2207
 
2118
2208
  Marking a key optional decides whether the payload has to return it, not how the key is written once it's returned. The `satisfies` type lists exactly the keys the payload returned, each one required.
2119
2209
 
2120
- Two kinds of value always need `#[TsCasts]`. The first is a class or enum named in the docblock, because a docblock string carries no import path. The second is any value typed as a model or a resource. A metadata value doesn't have to match either interface, so the package never imports one for it.
2210
+ An enum named in the docblock is imported from the generated enums, at any depth, so `pair: array{role: Role}` publishes `pair: { role: RoleType }`. So is one named in a `#[TsCasts]` entry with no `import`, when the key's value holds that enum. Two kinds of value still need a `#[TsCasts]` entry with an `import`. The first is any other class the docblock names at any depth, such as a model or an API resource, because a docblock string carries no import path. The second is a model or a resource the method body returns, because a metadata value doesn't have to match either interface, so the package never imports one for it. Without the entry, the companion fails, and the error names the model, the key and its type.
2121
2211
 
2122
2212
  Every returned key must end up with a type, and every required key must be returned. Otherwise the companion fails, and the error names the model and the keys.
2123
2213
 
@@ -2294,8 +2384,8 @@ export interface WarehouseResource {
2294
2384
  The package types most properties from the resource's backing Eloquent model, using its database columns, casts, accessors, and relations. It looks for that model in this order:
2295
2385
 
2296
2386
  1. The `#[TsResource(model: User::class)]` attribute.
2297
- 2. A `@mixin` or `@extends` tag in the resource's own docblock. The class name resolves through the file's `use` imports.
2298
- 3. The nearest parent class whose docblock has a `@mixin` or `@extends` tag.
2387
+ 2. A `@mixin`, `@extends`, or `@property … $resource` tag in the resource's own docblock. The class name resolves through the file's `use` imports.
2388
+ 3. The nearest parent class whose docblock has one of those tags.
2299
2389
  4. A `$resource` property redeclared with a `@var` type, such as `/** @var User */ public $resource;`.
2300
2390
  5. Laravel's naming convention in reverse, so `App\Http\Resources\UserResource` maps to `App\Models\User`.
2301
2391
  6. A model whose `#[UseResource(UserResource::class)]` attribute names the resource. This attribute needs Laravel 12.29 or later.
@@ -2306,10 +2396,49 @@ Step 3 lets a subclass use its parent's model without repeating the docblock, wh
2306
2396
 
2307
2397
  If no model resolves, a property read from the model, such as `$this->id`, publishes `unknown`.
2308
2398
 
2309
- `$this->resource` holds the backing model, so a key that returns it whole publishes the model's interface. `'post' => $this->resource` publishes `post: Post`. If the resource redeclares `$resource` as nullable, such as `/** @var Post|null */ public $resource;` or `?Post`, the key keeps that `null`: `post: Post | null`.
2399
+ `$this->resource` holds the backing model, so a key that returns it whole publishes the model's interface. `'post' => $this->resource` publishes `post: Post`. If the resource declares `$resource` as nullable, such as `/** @var Post|null */ public $resource;`, `?Post`, or `@extends JsonResource<Post|null>`, the key keeps that `null`: `post: Post | null`.
2310
2400
 
2311
2401
  A `ResourceCollection` is backed by no model, whatever its docblock or `#[TsResource(model:)]` names, because its `$this->resource` holds the collected items. A model read in a collection, such as `$this->title`, publishes `unknown`. See [Reading `$this->resource`](#reading-this-resource).
2312
2402
 
2403
+ #### Resources That Wrap Other Classes
2404
+
2405
+ A resource can wrap a class that isn't a model, such as a value object. Name the class in an `@extends JsonResource<X>`, `@mixin X`, or `@property X $resource` tag, or redeclare `$resource` with `@var X`. Reads through `$this->resource` and through the resource itself then take the types that class declares:
2406
+
2407
+ ```php
2408
+ /**
2409
+ * @extends JsonResource<PostStats>
2410
+ */
2411
+ class StatsSummaryResource extends JsonResource
2412
+ {
2413
+ public function toArray(Request $request): array
2414
+ {
2415
+ return [
2416
+ 'views' => $this->resource->views,
2417
+ 'shares' => $this->shares,
2418
+ 'summary' => $this->summary(),
2419
+ ];
2420
+ }
2421
+ }
2422
+ ```
2423
+
2424
+ `PostStats` declares `public float $views`, `public int $shares`, and `summary(): string`, so the resource publishes:
2425
+
2426
+ ```typescript
2427
+ export interface StatsSummaryResource {
2428
+ views: number;
2429
+ shares: number;
2430
+ summary: string;
2431
+ }
2432
+ ```
2433
+
2434
+ A tag that names a class other than a model stops the naming-convention and `#[UseResource]` guesses, because the resource doesn't wrap a model. The guess stands only when the guessed model is an instance of the class the tag names, such as `@mixin Arrayable`, an interface every model implements. `#[TsResource(model:)]` always wins over the tag.
2435
+
2436
+ A tag that names no class the package can load, such as an IDE helper's `@mixin IdeHelperPost`, is skipped, and so is one that names `Model` itself or the `Eloquent` alias. The model the other steps find still applies.
2437
+
2438
+ A tag can also name an intersection of a model and an interface it implements. With `@extends JsonResource<Post&HasLabel>`, `$this->title` reads the `Post` column and `$this->label()` reads the method `HasLabel` declares, so both publish `string`.
2439
+
2440
+ A subclass that redeclares `$resource` with its own `@var` decides what an inherited `toArray()` reads, because PHP has only one `$resource` property.
2441
+
2313
2442
  ### Supported `toArray()` Patterns
2314
2443
 
2315
2444
  These sections cover the Laravel resource features you use in `toArray()`. Each one shows the PHP you write and the TypeScript it produces.
@@ -2332,9 +2461,9 @@ name: string;
2332
2461
  status: StatusType;
2333
2462
  ```
2334
2463
 
2335
- `$this->resource->name` reads the same attribute, so it publishes the same type. A property you declare on the resource class itself, such as a promoted constructor parameter, takes its type from that declaration. It wins over a model attribute with the same name, as it does in PHP.
2464
+ `$this->resource->name` reads the same attribute, so it publishes the same type. A property you declare on the resource class itself, such as a promoted constructor parameter, takes its type from that declaration. It wins over a model attribute with the same name, as it does in PHP. A `@var` docblock on the property names classes through the imports of the file that declares it, so a property a trait declares uses the trait's imports. A promoted property with no `@var` takes its type from the constructor's `@param`, as PHPStan reads it.
2336
2465
 
2337
- An untyped property that nothing in the class, its parents, or its traits writes takes its default's type, so `protected $stage = Status::Draft;` publishes `StatusType`. A protected or private one declared without a value, such as `protected $name;`, publishes `null`.
2466
+ An untyped property publishes its default's type joined with each value the resource, its parents, its traits, or its children write to it, so `protected $stage = Status::Draft;` publishes `StatusType`, and a protected or private one declared without a value, such as `protected $name;`, publishes `null`. Writes include element writes and writes inside a closure, typed by the closure's parameters and `use` imports, so `protected $sizes = ['small' => 1];` extended by `$this->sizes['large'] = 2;` publishes `{ small: number; large?: number }`. A write in a trait method the resource overrides doesn't count. The property publishes `unknown` when a write is a value from an untyped parameter, a by-reference call such as `sort($this->sizes)`, or an `unset()` of the whole property.
2338
2467
 
2339
2468
  #### Conditional Methods
2340
2469
 
@@ -2470,7 +2599,17 @@ export interface PostResource {
2470
2599
  }
2471
2600
  ```
2472
2601
 
2473
- When the package can't type the value of `whenHas()` or `whenAppended()`, the property publishes `unknown`, not the attribute's type, because the value replaces the attribute in the response. `json_decode()` returns `mixed`, and a plain title decodes to `null`, so `title_unresolvable` is `unknown`. To type it, give the closure a native return type: `fn ($title): ?string => json_decode($title)` publishes `string | null`. A `@return` docblock on the closure doesn't type it.
2602
+ When the package can't type the value of `whenHas()` or `whenAppended()`, the property publishes `unknown`, not the attribute's type, because the value replaces the attribute in the response. `json_decode()` returns `mixed`, and a plain title decodes to `null`, so `title_unresolvable` is `unknown`. To type it, give the closure a native return type, or a `@return` docblock written just before the closure:
2603
+
2604
+ ```php
2605
+ 'title_typed' => $this->whenHas('title', fn ($title): ?string => json_decode($title)),
2606
+ 'title_documented' => $this->whenHas('title',
2607
+ /** @return string|null */
2608
+ fn ($title) => json_decode($title),
2609
+ ),
2610
+ ```
2611
+
2612
+ Both properties publish `string | null`, and both stay optional. The package reads the docblock only on a closure with no native return type, and ignores a vague one, such as `@return mixed`. A docblock written before the whole call, or above the array item, describes the call's value rather than the closure, so it isn't read. To type the key itself, use [`#[TsCasts]`](#overriding-property-types-with-tscasts).
2474
2613
 
2475
2614
  `whenExistsLoaded()` keeps `boolean` for a value it can't type. Without a value argument, `whenHas('phone')` types from its column, and `whenExistsLoaded('user')` publishes `boolean`.
2476
2615
 
@@ -2679,6 +2818,23 @@ visibility_from_helper: AsEnum<typeof Visibility> | null;
2679
2818
 
2680
2819
  Wrapping a conditional value, as in `EnumResource::make($this->whenHas('status'))`, makes the property optional, as the conditional method alone would.
2681
2820
 
2821
+ `EnumResource::make(Status::tryFrom($value))` adds `| null`, because `tryFrom()` returns `null` for a value that matches no case. A `map()` that wraps each element is different: kept as a collection, it sends `[]` for an element whose enum is `null`. Laravel turns an empty `EnumResource` into `null` only inside an array, so end the chain with `->all()` to get `null` instead:
2822
+
2823
+ ```php
2824
+ 'roles' => $this->members
2825
+ ->map(fn (User $user) => EnumResource::make($user->role)),
2826
+ 'role_list' => $this->members
2827
+ ->map(fn (User $user) => EnumResource::make($user->role))
2828
+ ->all(),
2829
+ ```
2830
+
2831
+ The two keys publish what each sends for a member with no role:
2832
+
2833
+ ```typescript
2834
+ roles: (AsEnum<typeof Role> | never[])[];
2835
+ role_list: (AsEnum<typeof Role> | null)[];
2836
+ ```
2837
+
2682
2838
  A ternary that wraps only one of its arms keeps both shapes. The property publishes a union, with the import each side needs, even inside an inline array:
2683
2839
 
2684
2840
  ```php
@@ -2816,7 +2972,7 @@ A closure or an arrow function in value position is typed from what it returns:
2816
2972
  }),
2817
2973
  ```
2818
2974
 
2819
- This works wherever a value goes, including `when()`, `whenLoaded()`, `whenNotNull()`, `merge()`, and `mergeWhen()`.
2975
+ This works wherever a value goes, including `when()`, `whenLoaded()`, `whenNotNull()`, `merge()`, and `mergeWhen()`. When the package can't type what a closure returns, the closure's native return type types the value, and so does a `@return` docblock on a closure with no native return type, as [`whenHas()`, `whenAppended()`, and `whenExistsLoaded()`](#whenhas-whenappended-and-whenexistsloaded-type-from-the-value-you-pass) shows.
2820
2976
 
2821
2977
  A closure that builds an array in a variable and returns it publishes the keys its writes set, as [Building the Array in a Variable](#building-the-array-in-a-variable) describes:
2822
2978
 
@@ -2895,7 +3051,7 @@ Values you compute in `toArray()` get types too: method calls, property reads on
2895
3051
 
2896
3052
  #### Method Return Types
2897
3053
 
2898
- A method call takes its type from the called method's signature: its native return type, or its `@return` docblock when the native type is missing or vague. This works for calls on enum casts, date casts, models, Eloquent collections, value objects, and services resolved from the container:
3054
+ A method call takes its type from the called method's signature: its native return type, or its `@return` docblock when the native type is missing or vague. When a method has more than one of `@phpstan-return`, `@psalm-return`, and `@return`, the package reads them in that order, as PHPStan does, and a vague one, such as `array<string, mixed>`, yields to a precise one. This works for calls on enum casts, date casts, models, Eloquent collections, value objects, and services resolved from the container:
2899
3055
 
2900
3056
  ```php
2901
3057
  public function toArray(Request $request): array
@@ -2929,6 +3085,8 @@ export interface PostResource {
2929
3085
 
2930
3086
  A property read works the same way. Once `$post` holds a `Post`, `$post?->author?->name` publishes `string | null`. A value object's public property takes its declared type, so `$this->stats?->views` publishes `number | null`. A `?->` adds `| null` to the result once, however many steps use it.
2931
3087
 
3088
+ A model or an enum named in a `@return` shape keeps its type at any depth, and the file imports it. A method documented `@return array{owner: User, count: int}` publishes `{ owner: User; count: number }`, whether you call it on the resource, on a service, or statically. Two kinds of shape publish each model and enum in them as `unknown`: one that also names another class, such as an API resource, and one that spells a class's name as a string literal or a key, as in `array{kind: 'User', owner: User}`.
3089
+
2932
3090
  When the declaration says too little, as with no return type, `mixed`, or a bare `array`, the method's own `return` statements set the type:
2933
3091
 
2934
3092
  ```php
@@ -2976,10 +3134,12 @@ public function total(): mixed
2976
3134
  }
2977
3135
  ```
2978
3136
 
2979
- `$this->resource->total()` calls the model's method directly, so it publishes the model's type. When neither the resource method's declaration nor its body types the call, the key publishes `unknown`, never the model method's type. Give the method a return type to fix it. The same holds for a `$resource` redeclared as a class other than a model, such as `/** @var CartTotals */ public $resource;`. If `CartTotals` doesn't declare the method you call, the key publishes `unknown`, because Laravel throws there.
3137
+ `$this->resource->total()` calls the model's method directly, so it publishes the model's type. When neither the resource method's declaration nor its body types the call, the key publishes `unknown`, never the model method's type. Give the method a return type to fix it. The same holds for a resource that [wraps a class other than a model](#resources-that-wrap-other-classes), such as one declared with `@extends JsonResource<CartTotals>` or `/** @var CartTotals */ public $resource;`. If `CartTotals` doesn't declare the method you call, the key publishes `unknown`, because Laravel throws there.
2980
3138
 
2981
3139
  Some of Laravel's own methods declare loose types, so the package reads the model instead. `getKey()` publishes the model's key type, `number` or `string`, and `modelKeys()` publishes a list of it. That's why `comment_ids` above is `number[]`. `resolveRouteBinding()` publishes the model you call it on, or `null`, so `$this->author?->resolveRouteBinding($this->user_id)` publishes `User | null`.
2982
3140
 
3141
+ `getAttribute()` and `getAttributeValue()` with a literal name publish what reading the attribute as a property would. On a `Post` resource, `$this->getAttribute('title')` and `$this->resource->getAttributeValue('title')` publish `string`, as `$this->title` does, and `$this->resource->getAttribute('author')` publishes the relation's type, `User`. That works on a relation's model and a closure parameter too, so `$this->whenLoaded('author', fn ($author) => $author->getAttribute('name'))` publishes `string` as an optional property. A name the model doesn't declare publishes `unknown`, and so does a relation read through `getAttributeValue()`, which returns no relation.
3142
+
2983
3143
  `getKey()` publishes the key type on any model the package can name, including one a variable holds, such as a `whenLoaded()` closure parameter, a `map()` element, or a helper's `Post $post` parameter. So `$this->comments->map(fn ($comment) => $comment->getKey())` publishes `number[]`.
2984
3144
 
2985
3145
  A model that no database row backs yet has no key, so its `getKey()` adds `| null`. That covers a model you build with `new`, `replicate()`, `replicateQuietly()` or `newInstance()`, and one that a query, a relation or a factory builds without saving it:
@@ -3176,67 +3336,51 @@ private function summary(Request $request): array
3176
3336
 
3177
3337
  If one `return` can't be typed, or the method yields, the property publishes `unknown`.
3178
3338
 
3179
- When you use the method's result as a value, a value in the array that is an enum or a model publishes `unknown`, because a method body can't supply the import it needs. The rest of the shape keeps its types, and an enum's `->value` or `->name` publishes the literal union of its values or names, as [Reading `->value` and `->name`](https://tolki.abe.dev/ts/enums.html#reading-value-and-name) describes. Spreading the same method keeps an enum's type. To type that value, build the array in `toArray()` itself, or override the property with [`#[TsCasts]`](#overriding-property-types-with-tscasts) and a type your frontend exports, as in `['type' => 'StatusPayload', 'import' => '@/types/payloads']`. An entry imports only a type it names whole, so a type named inside a shape you write in the entry isn't imported.
3339
+ When you use the method's result as a value, its array publishes what the same expressions publish in `toArray()`. That includes models, API resources, and enums, and the file imports what they name. One value differs. A backed enum case you write out, such as `PostStatus::Draft`, publishes the value it sends, `0`, instead of the enum's alias. A list of such cases publishes a list of their values, such as `(0 | 1)[]`.
3180
3340
 
3181
- Here a `Post` casts `status` to the int-backed `PostStatus` enum, whose cases are `Draft = 0` and `Published = 1`. The resource uses `statusLabel()` as a value, then spreads it:
3341
+ Here a `Post` casts `status` to the int-backed `PostStatus` enum, whose cases are `Draft = 0` and `Published = 1`, and `author` is a `BelongsTo` relation whose foreign key isn't nullable. The resource uses `card()` as a value:
3182
3342
 
3183
3343
  ```php
3184
3344
  public function toArray(Request $request): array
3185
3345
  {
3186
3346
  return [
3187
- 'label' => $this->statusLabel($this->status),
3188
- ...$this->statusLabel($this->status),
3347
+ 'card' => $this->card(),
3189
3348
  ];
3190
3349
  }
3191
3350
 
3192
- private function statusLabel(PostStatus $status): array
3351
+ private function card(): array
3193
3352
  {
3194
- return ['name' => $status->name, 'value' => $status->value];
3353
+ return [
3354
+ 'author' => $this->author,
3355
+ 'status' => $this->status,
3356
+ 'status_resource' => EnumResource::make($this->status),
3357
+ 'first_status' => PostStatus::Draft,
3358
+ ];
3195
3359
  }
3196
3360
  ```
3197
3361
 
3198
- `label` publishes the literal unions, and the spread keys publish the enum's aliases:
3362
+ Each member keeps its type, and `first_status` publishes the case's value:
3199
3363
 
3200
3364
  ```typescript
3201
- import type { PostStatusKind, PostStatusType } from "../../enums";
3202
-
3203
- export interface PostLabelResource {
3204
- label: { name: "Draft" | "Published"; value: 0 | 1 };
3205
- name: PostStatusKind;
3206
- value: PostStatusType;
3207
- }
3208
- ```
3209
-
3210
- A model's own `toArray()`, called as a value, publishes `Record<string, unknown>`, because the relations it includes depend on what's loaded at runtime. A relation's collection, as in `$this->comments->toArray()`, publishes `Record<string, unknown>[]`. To publish the model's keys, spread it instead, as [Model `toArray()` Spread](#model-toarray-spread) shows.
3211
-
3212
- An `only()` or `except()` call names no class, so its result keeps its shape:
3213
-
3214
- - A literal key list publishes its inline shape, with any enum- or model-typed member left `unknown`.
3215
- - A runtime key list publishes `Record<string, unknown>`.
3216
- - A to-many relation publishes `unknown[]`.
3217
-
3218
- The same applies when the method reads an accessor whose getter calls `only()` or `except()`. A model that overrides `only()` or `except()` with a declared return type publishes that type instead. A model return, such as `: static`, becomes an object with the model's columns and appended accessors, narrowed to the literal keys. An enum or other class return leaves the value `unknown`.
3365
+ import { type AsEnum } from "@tolki/ts";
3219
3366
 
3220
- This `Comment` method shows each case:
3367
+ import { PostStatus } from "../../enums";
3368
+ import type { PostStatusType } from "../../enums";
3369
+ import type { User } from "../../models";
3221
3370
 
3222
- ```php
3223
- // On Comment, read from a resource as 'summary' => $this->relationSummary()
3224
- public function relationSummary(): array
3225
- {
3226
- return [
3227
- 'id' => $this->id,
3228
- 'author' => $this->user->only(['id', 'name']),
3229
- 'author_role' => $this->user?->only(['id', 'role']),
3230
- 'replies' => $this->replies->only([1, 2]),
3231
- ];
3371
+ export interface PostCardResource {
3372
+ card: {
3373
+ author: User;
3374
+ status: PostStatusType;
3375
+ status_resource: AsEnum<typeof PostStatus>;
3376
+ first_status: 0;
3377
+ };
3232
3378
  }
3233
3379
  ```
3234
3380
 
3235
- The `role` column is an enum, so it's left `unknown`, and the to-many `replies` publishes `unknown[]`:
3381
+ Written in `toArray()` itself, or spread with `...$this->card()`, `first_status` publishes `PostStatusType`.
3236
3382
 
3237
- ```typescript
3238
- summary: { id: number; author: { id: number; name: string }; author_role: { id: number; role: unknown } | null; replies: unknown[] };
3239
- ```
3383
+ A model's own `toArray()`, called as a value, publishes `Record<string, unknown>`, because the relations it includes depend on what's loaded at runtime. A relation's collection, as in `$this->comments->toArray()`, publishes `Record<string, unknown>[]`. To publish the model's keys, spread it instead, as [Model `toArray()` Spread](#model-toarray-spread) shows.
3240
3384
 
3241
3385
  ##### Resource Macros
3242
3386
 
@@ -3253,7 +3397,7 @@ JsonResource::macro('label', function (): string {
3253
3397
  'model_label' => $this->resource->label(), // model_label: number
3254
3398
  ```
3255
3399
 
3256
- `$this->resource->label()` calls the model directly, so it keeps the model's type. `$this?->label()`, `static::label()`, `self::label()` and `$this::label()` reach the macro, as `$this->label()` does. A method the resource declares or inherits, such as `whenLoaded()`, runs before any macro with its name, so a macro never changes it.
3400
+ `$this->resource->label()` calls the model directly, so it keeps the model's type. `$this?->label()`, `static::label()`, `self::label()` and `$this::label()` reach the macro, as `$this->label()` does. A method the resource declares or inherits, such as `whenLoaded()`, runs before any macro with its name, so a macro doesn't change it. In a parent resource's body, `self::label()` looks only at that parent: if the parent doesn't declare `label()`, the macro runs even when the child declares one, and the key publishes the macro's type.
3257
3401
 
3258
3402
  The package types a macro from its native return type, then its `@return` docblock, then its body. It reads the body without the values the call passes, so a body whose result depends on its arguments publishes `unknown`. It doesn't read the body of a closure declared outside a class method, such as in `bootstrap/app.php`. To type such a macro, give the closure a return type. A `@return` docblock works only on a closure declared inside a class, such as in a service provider's `boot()` method.
3259
3403
 
@@ -3364,7 +3508,34 @@ Some variables still publish `unknown`:
3364
3508
 
3365
3509
  Variables assigned inside a closure body follow the same rules within that closure. A reassignment inside an `if` branch that ends in `return` or `throw` applies only inside that branch, so the code after it keeps reading the original variable.
3366
3510
 
3367
- `preg_match()` writes its `$matches` as a list of strings. After `preg_match('/(\w+)-(\d+)/', $this->slug, $matches)`, both `$matches` and `$matches ?? []` publish `string[]`. A pattern with a named group, or a call that passes flags such as `PREG_OFFSET_CAPTURE`, writes the groups keyed by name or nested. The package doesn't type those groups, so `$matches ?? []` publishes `never[]`. A call that may not run, such as one inside an `if`, types `$matches` only when nothing else writes the variable.
3511
+ `preg_match()` and `preg_match_all()` type their `$matches` from the pattern's groups and the flags you pass. After `preg_match('/(\w+)-(\d+)/', $this->slug, $matches)`, both `$matches` and `$matches ?? []` publish `string[]`. Named groups and flags change the shape:
3512
+
3513
+ ```php
3514
+ preg_match('/(?<first>B)/', $this->title, $named);
3515
+ preg_match('/(B)/', $this->title, $offset, PREG_OFFSET_CAPTURE);
3516
+ preg_match('/(B)(x)?/', $this->title, $nulls, PREG_UNMATCHED_AS_NULL);
3517
+ preg_match_all('/(B)/', $this->title, $all);
3518
+
3519
+ return [
3520
+ 'named' => $named,
3521
+ 'first' => $named['first'] ?? null,
3522
+ 'offset' => $offset ?? [],
3523
+ 'nulls' => $nulls ?? [],
3524
+ 'all' => $all,
3525
+ ];
3526
+ ```
3527
+
3528
+ Each key publishes the shape its call writes:
3529
+
3530
+ ```typescript
3531
+ named: { "0": string; first?: string; "1"?: string } | never[];
3532
+ first: string | null;
3533
+ offset: [string, number][];
3534
+ nulls: (string | null)[];
3535
+ all: string[][];
3536
+ ```
3537
+
3538
+ A named group's matches publish an object keyed by name and number, or `never[]` for the empty array a failed match leaves. A pattern the package can't read as a literal, such as one held in a variable, leaves `$matches ?? []` as `never[]`. A call that may not run, such as one inside an `if`, types `$matches` only when nothing else writes the variable.
3368
3539
 
3369
3540
  A literal key read on a variable that holds an array shape takes that key's type. With `$row = ['a' => 1, 'b' => 'x']`, `$row['b']` publishes `string`, and `$row['c'] ?? null`, a key the shape lacks, publishes `null`. A `map()` parameter and a method whose `@return` declares a shape work the same way, so `$this->pair()[1]` on a method declared `@return array{int, string}` publishes `string`.
3370
3541
 
@@ -3461,10 +3632,27 @@ if ($owner instanceof Post) {
3461
3632
  return $data; // post_title?: string; user_email?: string
3462
3633
  ```
3463
3634
 
3464
- The test can be one `instanceof`, negated or not, or an `||` chain of tests on the same variable, which narrows to any of their classes. A positive test can also join tests with `&&`. A positive test whose `||` joins two different variables narrows neither. A guard whose negated tests are joined with `||` narrows each, and one joined with `&&` narrows none. The test must read a local variable, a closure parameter, or a `foreach` value variable, not a property such as `$this->author`.
3635
+ The test can be one `instanceof`, negated or not, or an `||` chain of tests on the same variable, which narrows to any of their classes. A positive test can also join tests with `&&`. A positive test whose `||` joins two different variables narrows neither. A guard whose negated tests are joined with `||` narrows each, and one joined with `&&` narrows none. The test can read a local variable, a closure parameter, a `foreach` value variable, or a chain of property reads on `$this`, such as `$this->imageable`.
3465
3636
 
3466
3637
  A write to the variable between the test and the end of what it narrows cancels the narrowing, even for the reads before that write. A write through one of its members keeps the narrowing when it stores a literal the member's column holds, such as `$parent->title = 'Draft'`, or names no column or relation, such as `$parent->touched = true`. A write before the test doesn't matter, since the test checks the value it leaves.
3467
3638
 
3639
+ A test on a `$this` property chain narrows reads of that same chain, so you don't need a local first. Here `imageable` is a `morphTo`:
3640
+
3641
+ ```php
3642
+ if (! $this->imageable instanceof Post) {
3643
+ return ['title' => null];
3644
+ }
3645
+
3646
+ return ['title' => $this->imageable->title]; // title: string | null
3647
+ ```
3648
+
3649
+ Each spelling narrows on its own, so a test on `$this->resource->imageable` doesn't narrow a read of `$this->imageable`. Because code between the test and a read could change the property, the narrowing ends at a write to the chain, at any write through a local, and at most calls, such as `$this->reload()`, `PostResource::make($this->resource)`, or a call on a local. These calls keep it:
3650
+
3651
+ - The resource's own helpers, such as `when()` and `whenLoaded()`
3652
+ - Gate and policy checks
3653
+ - Laravel's `route()` and `url()`
3654
+ - A call that's passed no local, no `$this`, and no `$this->resource`, such as `Str::limit($this->imageable->title, 50)`
3655
+
3468
3656
  A read in a guard's own body, in a `return` placed before the guard, or in the `if` condition itself still sees every class the variable can hold.
3469
3657
 
3470
3658
  Narrowing applies to reads through the variable, such as `$parent->title`. A local's own value, as in `'parent' => $parent`, keeps its full union type. A closure parameter bound to one model is the exception: under a test for a published subclass of that model, its own value publishes the subclass, so `$this->whenLoaded('post', fn ($post) => $post instanceof DraftPost ? $post : null)` publishes `DraftPost | null`.
@@ -3497,7 +3685,6 @@ return [
3497
3685
  These forms don't narrow:
3498
3686
 
3499
3687
  - **The ternary's own value**: `'either' => $either` publishes the whole union. Only reads through the variable narrow.
3500
- - **An `if` that tests a property**: inside `if ($this->imageable instanceof Post) { ... }`, `$this->imageable` still reads every model the `morphTo` can hold. Assign it to a local and test that instead.
3501
3688
  - **A test on a different spelling of the arm's value**: a variable bound to a ternary that tests `$this->resource->imageable` against a `$this->imageable` arm isn't narrowed.
3502
3689
  - **Mixed conditions in a ternary**: a test joined with `&&`, or an `||` chain that mixes negated and plain tests.
3503
3690
  - **The arm the test doesn't prove**: `$this->resource instanceof SubscribedTeam ? null : $this->resource->subscriber` publishes `unknown`, since `Team` has no `subscriber` relation.
@@ -3525,7 +3712,7 @@ $picked = $this->id > 0 ? json_decode('"x"') : null; // string | null
3525
3712
 
3526
3713
  The annotation follows these rules:
3527
3714
 
3528
- - **Placement**: it sits on a `$x = ...;` statement anywhere in the method or closure body, including inside an `if` or a loop. It names the variable, as in `/** @var CartTotals $totals */`, or names none, as in `/** @var CartTotals */`.
3715
+ - **Placement**: it sits on a `$x = ...;` statement anywhere in the method or closure body, including inside an `if` or a loop. It names the variable, as in `/** @var CartTotals $totals */`, or names none, as in `/** @var CartTotals */`. A `@phpstan-var` or `@psalm-var` tag wins over a plain `@var`, as in PHPStan.
3529
3716
  - **Span**: it types the reads after that statement, up to the next statement that writes the variable. A loop that writes the variable ends the span where the loop starts. So an annotation also types a variable you reassign, until its next write. Inside a block, it types the reads after it in that block. Past the block, where the variable held a value before it, the annotated type joins that value. Where the variable held none, reads past the block aren't typed. With `$post = null;` before an `if` whose annotated assignment reads `/** @var Post|null $post */`, `$post?->title` after the `if` publishes `string | null`.
3530
3717
  - **Precedence**: it applies only where the package's own reading of the value is `unknown`, or is only the `null` left after an arm it can't type was dropped. Any other reading stands, whatever the annotation says: `/** @var int $n */ $n = $this->title;` still publishes `string`. To override a type the package got wrong, use [`#[TsCasts]`](#overriding-property-types-with-tscasts).
3531
3718
 
@@ -3538,14 +3725,18 @@ A write the package can't type keeps a model parameter's model, so after `$autho
3538
3725
  The annotation's type counts only when it's built from these forms, and when every part of it resolves:
3539
3726
 
3540
3727
  - Scalars: `int`, `string`, `bool`, `float`, `null`, `true`, and `false`
3541
- - A class, interface, or enum that the file imports or writes in full
3542
- - `list<X>`, `array<int, X>`, `array<string, X>`, and `array<'a'|'b', X>`
3728
+ - A class, interface, or enum that the file imports, writes in full, or declares in its own namespace
3729
+ - `self`, `static`, and `parent`, which name the classes `self::`, `static::`, and `parent::` reach in that method, as in an [inherited `toArray()`](#inheriting-a-parent-toarray). The variable may hold a subclass, so a read of a method or property a subclass can override takes its declared type, and publishes `unknown` where it has none. A closure parameter typed `self` or `parent` reads the same way.
3730
+ - `X[]`, `list<X>`, `array<int, X>`, `array<string, X>`, `array<int|string, X>`, `array<array-key, X>`, and `array<'a'|'b', X>`
3543
3731
  - `array{...}` and `object{...}` shapes with plain or quoted keys, and `list{...}` tuples
3544
- - `Collection<K, X>`, for both Laravel's support collection and its Eloquent collection
3732
+ - `Collection<X>` and `Collection<K, X>`, for both Laravel's support collection and its Eloquent collection
3733
+ - A type alias the class declares with `@phpstan-type`, or imports with `@phpstan-import-type`, under its own name or an `as` name
3545
3734
  - A `callable` as a shape's member, which publishes `unknown`
3546
3735
  - Unions of these forms, such as `Comment|User|null` or `list<User>|User`, and `?` before any form
3547
3736
 
3548
- Any other type is ignored, so write `list<int>` instead of `int[]`. A model or enum inside a shape is ignored too. A `?` before a shape adds `| null` even when a member already holds `null`, so `?array{a: ?int}` publishes `{ a: number | null } | null`.
3737
+ Any other type is ignored. A key that can be an `int` or a `string`, as in `array<int|string, Comment>` or `array<array-key, Comment>`, publishes both shapes PHP can send, `Comment[] | Record<string, Comment>`. A model or an enum inside a shape keeps its type, so `array{author: User, status: Status}` publishes `{ author: User; status: StatusType }`. A `?` before a shape adds `| null` even when a member already holds `null`, so `?array{a: ?int}` publishes `{ a: number | null } | null`.
3738
+
3739
+ A helper's or a closure's `@param` tag reads the same forms where the value passed in can't be typed. With `@param Collection<int, Comment> $comments`, a read such as `$comments->first()?->content` publishes `string | null`, and with `@param Pair $pair`, where `Pair` is a `@phpstan-type` alias, `$pair` takes the alias's shape. Where the value passed in is typed, its type wins over the tag.
3549
3740
 
3550
3741
  #### Collection Pipelines
3551
3742
 
@@ -3579,7 +3770,9 @@ These helpers and methods publish as follows:
3579
3770
  - **`all()` and `values()`**: a collection and the array behind it both publish `X[]`, so `all()` changes nothing. A method that breaks sequential keys, such as `filter()`, `sortBy()`, or `keyBy()`, adds a `Record<string, X>` arm, because `json_encode()` writes such a collection as an object. The arm stays through a local and through a later `map()`. `values()` restores sequential keys and removes that arm.
3580
3771
  - **`collect()`**: the element type comes from the argument, and the `map()` parameter holds that element, which is why `$word` above is a `string`. On its own, `collect([...])` publishes the list or object its array encodes as, such as `number[]` for `collect([1, 2])` or `{ title: string }` for `collect(['title' => $this->title])`. `collect()` with no argument publishes `never[]`. A bare array literal publishes the same way, so `['a', 'b']` publishes `string[]`. A list holding an element the package can't type publishes `unknown[]`.
3581
3772
  - **`data_get()`**: `data_get($target, 'a.b')` publishes what `$target?->a?->b` would. A default joins the type instead of removing `null`, because `data_get()` returns the default only when the key is missing, not when its value is `null`.
3582
- - **`map()` parameters**: the callback's parameter holds the collection's element, with or without a type hint, whether the collection comes from a relation, a local, a `whenLoaded()` parameter, `getRelation()`, a query's `get()`, or `collect()`. Every read through it is typed, chained and nullsafe reads included. A class type hint, such as `fn (Comment $comment)` or a value object's class, types the parameter whatever the collection holds. A write that replaces the parameter is followed into the body.
3773
+ - **`keys()`**: publishes the list of the keys, `number[]` for a list and `string[]` for a `Record<string, X>`. A literal array lists its own keys, so `collect(['a' => 1, 200 => 'x'])->keys()->all()` publishes `('a' | 200)[]`.
3774
+ - **`map()` parameters**: the callback's parameter holds the collection's element, with or without a type hint, whether the collection comes from a relation, a local, a `whenLoaded()` parameter, `getRelation()`, a query's `get()`, or `collect()`. Every read through it is typed, chained and nullsafe reads included. A class type hint, such as `fn (Comment $comment)` or a value object's class, types the parameter whatever the collection holds. A scalar type hint holds the value PHP converts the element to, so `collect(['5'])->map(fn (int $v) => $v)->all()` publishes `number[]`. A write that replaces the parameter is followed into the body.
3775
+ - **`map()` callbacks**: besides a closure, the callback can be a first-class callable, such as `$this->shout(...)`, or a callable string, such as `'strtoupper'`. A `map()` over a `Record<string, X>` keeps its string keys, so it publishes a `Record` of what the callback returns.
3583
3776
 
3584
3777
  Here `PromoCode` is a value object with a `string` property `code`:
3585
3778
 
@@ -3623,6 +3816,79 @@ A chain can start at `$this->resource` too. `$this->resource->comments->map(fn (
3623
3816
 
3624
3817
  `first()`, `last()` and `firstWhere()` on a collection of models return one of its models or `null`, so a read through them with `?->` is typed. That covers a relation's collection, a local holding one, and a variable an inline `@var Collection<int, Comment>` declares. `$this->comments->first()?->content` publishes `string | null`, and so does the same read after `last()`, `firstWhere('is_flagged', true)`, or `find()` with one literal key, such as `find(1)`. After a `first()` or `last()` call that passes a default, such as `first(null, 'none')`, the read publishes `unknown`, because Laravel returns that default when no model matches.
3625
3818
 
3819
+ ##### Array Functions
3820
+
3821
+ PHP's array functions keep the element type too. `array_map()` with one array keeps that array's keys, so a list maps to a list and a string-keyed array to an object. With two or more arrays it publishes a list, and a `null` callback zips the arrays into tuples. The callback can be any callable, as with `map()`:
3822
+
3823
+ ```php
3824
+ public function toArray(Request $request): array
3825
+ {
3826
+ return [
3827
+ 'messages' => array_map(fn (array $row): string => $row['message'], $this->rows()),
3828
+ 'doubled' => array_map(fn (int $count): int => $count * 2, ['low' => 1, 'high' => 2]),
3829
+ 'zipped' => array_map(null, $this->labels(), $this->counts()),
3830
+ 'names' => array_map('strtoupper', $this->comments->pluck('content')->all()),
3831
+ ];
3832
+ }
3833
+ ```
3834
+
3835
+ Here `rows()` returns `list<array{message: string}>`, `labels()` a `list<string>`, and `counts()` a `list<int>`:
3836
+
3837
+ ```typescript
3838
+ export interface ArrayMapResource {
3839
+ messages: string[];
3840
+ doubled: { low: number; high: number };
3841
+ zipped: [string | null, number | null][];
3842
+ names: string[];
3843
+ }
3844
+ ```
3845
+
3846
+ `array_keys()` publishes the list of the keys, as `keys()` does, so `array_keys(['a' => 1, 'b' => 2])` publishes `('a' | 'b')[]`.
3847
+
3848
+ `array_filter()` of an array shape makes each key optional and leaves out a key that only ever holds `null`. `array_values()` of the result publishes the list of the values left:
3849
+
3850
+ ```php
3851
+ 'shape' => array_filter(['a' => $this->title, 'b' => $this->published_at]),
3852
+ 'no_null' => array_filter(['a' => $this->title, 'b' => null]),
3853
+ 'values' => array_values(array_filter(['a' => $this->title, 'b' => $this->published_at])),
3854
+ ```
3855
+
3856
+ Here `published_at` is a nullable column:
3857
+
3858
+ ```typescript
3859
+ shape: { a?: string; b?: string };
3860
+ no_null: { a?: string };
3861
+ values: string[];
3862
+ ```
3863
+
3864
+ A filter that keeps no key sends `[]`, not `{}`. Reading a key on it still gives `undefined`, as the optional keys allow, but code that checks for an array, such as `Array.isArray()`, sees one.
3865
+
3866
+ PHP throws a `TypeError` when you pass a collection to `array_map()`, `array_keys()`, `array_values()`, or `array_filter()`, so `ts:publish` warns and names the line. Call `->values()->all()` on the collection first.
3867
+
3868
+ #### Query Chains
3869
+
3870
+ A query chain that starts at a model is typed step by step, as in [page props](https://tolki.abe.dev/ts/routing.html#what-the-props-expression-can-be):
3871
+
3872
+ ```php
3873
+ return [
3874
+ 'author' => User::find(1),
3875
+ 'author_name' => User::find(1)?->name,
3876
+ 'latest' => Post::query()->first(),
3877
+ 'first_id' => Post::query()->pluck('id')->first(),
3878
+ 'admins' => User::query()->where('id', 1)->get(),
3879
+ ];
3880
+ ```
3881
+
3882
+ Each chain publishes what its last step returns:
3883
+
3884
+ ```typescript
3885
+ author: User | null;
3886
+ author_name: string | null;
3887
+ latest: Post | null;
3888
+ first_id: number | null;
3889
+ admins: User[];
3890
+ ```
3891
+
3626
3892
  ### Spreads and Inheritance
3627
3893
 
3628
3894
  A resource can build its array from its parent class, its traits, and its own helper methods. Each one adds its properties to the interface.
@@ -3699,7 +3965,7 @@ The nearest class up the parent chain that declares a `toArray()` provides the s
3699
3965
  The package reads the inherited body as PHP runs it for the child:
3700
3966
 
3701
3967
  - `$this->` and `static::` reach the child, so a method, constant, or property the child overrides publishes the child's type. That includes a helper that `toArray()` spreads.
3702
- - `self::` reaches the class that declares the body, and `parent::` reaches that class's parent.
3968
+ - `self::` reaches the class that declares the body, and `parent::` reaches that class's parent. Spreads follow the same rule: `...parent::extra()` adds the keys of the parent's `extra()`, as `...self::extra()` and `...static::extra()` add those of the method each reaches. A private or abstract parent method adds none because PHP throws on that call, and neither does one whose body the package can't read in full.
3703
3969
  - A `private` member stays the one in the class that declares `toArray()`, because PHP never overrides one.
3704
3970
 
3705
3971
  ```php
@@ -3951,7 +4217,7 @@ export interface PostResource {
3951
4217
  }
3952
4218
  ```
3953
4219
 
3954
- Multi-line `@return` shapes work too:
4220
+ Multi-line `@return` shapes work too, as long as the type starts on the tag's own line, as PHPStan requires:
3955
4221
 
3956
4222
  ```php
3957
4223
  /**
@@ -4257,7 +4523,7 @@ trait GathersPermissions
4257
4523
  /** Untyped, so only the docblocks above can type what it returns. */
4258
4524
  protected function opaque()
4259
4525
  {
4260
- return $this->resource->getAttribute('title');
4526
+ return json_decode($this->resource->payload);
4261
4527
  }
4262
4528
  }
4263
4529
  ```
@@ -4277,13 +4543,45 @@ export interface PostPermissionsResource {
4277
4543
  Both forms of `@return` count:
4278
4544
 
4279
4545
  - **An `array{...}` shape**: each key gets its own type, and a key written `key?:` also becomes optional. A string or number literal type, such as `'draft'|'live'` or `1|2|3`, publishes as written.
4280
- - **`array<string, V>`**: `V` types every key the body left `unknown`.
4546
+ - **`array<string, V>`**: `V` types every key the body left vague.
4281
4547
 
4282
4548
  `toArray()`'s own `@return array{...}` fills keys the same way.
4283
4549
 
4284
- The body always wins. The docblock fills only a key the body left `unknown`, or an [interpolated key's](#interpolated-keys) value that the body left `unknown | undefined`, so a stale `@return` can't overwrite a type the package already knows.
4550
+ The body wins wherever it's specific, so a stale `@return` can't overwrite a type the package already knows. The docblock fills only a key the body left vague, such as `unknown`, `unknown[]`, or `Record<string, unknown>`, and keeps any `| null` the body found. It also fills an [interpolated key's](#interpolated-keys) value that the body left `unknown | undefined`.
4551
+
4552
+ A shape value that names a model, an enum, or an API resource keeps it at any depth, and the file imports it. Here `tags` is a nullable column cast to `'array'`, which publishes `unknown[] | null` on its own, and `json_decode()` returns a value the package can't type:
4553
+
4554
+ ```php
4555
+ /**
4556
+ * @return array{
4557
+ * tags: list<string>,
4558
+ * extra: array{author: User, status: PostStatus},
4559
+ * }
4560
+ */
4561
+ public function toArray(Request $request): array
4562
+ {
4563
+ return [
4564
+ 'tags' => $this->tags,
4565
+ 'extra' => json_decode($this->extra_json, true),
4566
+ ];
4567
+ }
4568
+ ```
4569
+
4570
+ The docblock fills both keys, and `tags` keeps its `| null`:
4571
+
4572
+ ```typescript
4573
+ import type { PostStatusType } from "../../enums";
4574
+ import type { User } from "../../models";
4575
+
4576
+ export interface PostExtrasResource {
4577
+ tags: string[] | null;
4578
+ extra: { author: User; status: PostStatusType };
4579
+ }
4580
+ ```
4285
4581
 
4286
- A shape value that names a PHP class or enum is skipped, because a docblock can't carry its import. Type that key with `#[TsCasts]` and an `import` instead. A name that isn't a PHP class, such as a type you declare only in TypeScript, publishes as written in a spread method's `@return`. In `toArray()`'s own `@return`, the key stays `unknown`, so type it with `#[TsCasts]`.
4582
+ A spread method's fill keeps its classes only when you spread the method at the top level of `toArray()`. Spread inside a nested array, as in `'meta' => [...$this->extras()]`, each model, enum, or API resource the fill names publishes `unknown`. Type such a key with `#[TsCasts]` and an `import`.
4583
+
4584
+ A name that isn't a PHP class, such as a type you declare only in TypeScript, publishes as written in a spread method's `@return`. In `toArray()`'s own `@return`, the key stays `unknown`, so type it with `#[TsCasts]`.
4287
4585
 
4288
4586
  In a spread method, the branches count only while every `return` is an array literal, `[]`, or a variable the method builds. Otherwise, only the spread method's first `return` counts.
4289
4587
 
@@ -4802,11 +5100,13 @@ Here `pager` publishes `LengthAwarePaginator<UserResource> | null`.
4802
5100
 
4803
5101
  A call the collection forwards to `$this->resource`, such as `$this->first()` or `$this->total()`, publishes the same type. In a [key-preserving collection](#key-preserving-collections), the list type is `Record<string, UserResource>`. When no singular resource matches, each type holds `unknown`, such as `unknown[]` and `LengthAwarePaginator<unknown>`.
4804
5102
 
4805
- The package doesn't follow a collection pipeline on `$this->resource`, such as `map()`, `pluck()` or `values()`, or a read on the item `first()` returns, such as `$this->resource->first()?->name`. Each publishes `unknown`. Type such a key with [`#[TsCasts]`](#overriding-property-types-with-tscasts).
5103
+ A read on the item `first()` or `last()` returns takes the type of the singular resource's model. In a `PostCollection` that collects `PostResource`, `$this->resource->first()?->title`, `$this->collection->first()?->title`, and `$this->collection->last()?->title` each publish `string | null`.
5104
+
5105
+ The package doesn't follow a collection pipeline on `$this->resource`, such as `map()`, `pluck()` or `values()`. Each publishes `unknown`. Type such a key with [`#[TsCasts]`](#overriding-property-types-with-tscasts).
4806
5106
 
4807
5107
  #### Paginated Collections
4808
5108
 
4809
- A collection's interface covers what its `toArray()` returns. The `links` and `meta` keys Laravel adds to a paginated response, and any data you add with `with()` or `additional()`, aren't part of it. An Inertia page prop that passes a paginator to a resource collection gets its pagination members from the page prop's type instead, with the `meta` block of each paginator kind. See [Paginating Inline in the Render Call](https://tolki.abe.dev/ts/inertia.html#paginating-inline-in-the-render-call) on the Inertia page.
5109
+ A collection's interface covers what its `toArray()` returns. The `links` and `meta` keys Laravel adds to a paginated response, and any data you add with `with()` or `additional()`, aren't part of it. An Inertia page prop that passes a paginator to a resource collection gets its pagination members from the page prop's type instead, with the `meta` block of each paginator kind. An Inertia prop's type also carries the `with()` and `additional()` keys. See [Paginating Inline in the Render Call](https://tolki.abe.dev/ts/inertia.html#paginating-inline-in-the-render-call) on the Inertia page.
4810
5110
 
4811
5111
  Over a paginator, Laravel merges a `meta` or `links` key that your `toArray()` returns beside `data` into its own pagination block with `array_merge_recursive()`, and it merges the `with()` and `additional()` data the same way. A key your `toArray()` adds, such as `links.self`, is in the page prop's type. A key that two of these name, such as `meta.total`, is sent as a list of both values, such as `[3, 3]`, while the type still says `number`. Give your key another name, or remove from `paginationInformation()` only the key your `toArray()` also sends. The package doesn't read `paginationInformation()`, so any other change there leaves the published pagination type wrong.
4812
5112
 
@@ -4982,7 +5282,8 @@ The package already types these shapes without an override:
4982
5282
  - A method call on an enum, a date, a model, or a service, and a property read on any of those or on a value object. See [Method Return Types](#method-return-types).
4983
5283
  - A value behind a local variable, a closure-local variable, or an `instanceof` guard. See [Local Variables and Narrowing](#local-variables-and-narrowing).
4984
5284
  - A collection chain, `data_get()`, and `only([...])` on any model. See [Collection Pipelines](#collection-pipelines) and [Attribute Filters on Any Model](#attribute-filters-on-any-model).
4985
- - A key that only some branches return, or one that a spread method's `@return` describes. See [Return Branches and `@return` Shapes](#return-branches-and-return-shapes).
5285
+ - A key that only some branches return, or one that `toArray()`'s or a spread method's `@return` describes. See [Return Branches and `@return` Shapes](#return-branches-and-return-shapes).
5286
+ - A model, an enum, or an API resource in the array of a method you use as a value. See [Methods Declared as a Bare `array`](#methods-declared-as-a-bare-array).
4986
5287
 
4987
5288
  `#[TsCasts]` is the right tool when the frontend owns the type and it needs its own import, or when a shape is dynamic. To type every value of a class that way, put [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) on the class instead.
4988
5289
 
@@ -5485,7 +5786,7 @@ final class PostScheduled implements ShouldBroadcast
5485
5786
 
5486
5787
  private function publishedAt() // no return type
5487
5788
  {
5488
- return $this->post->getAttribute('published_at');
5789
+ return json_decode($this->post->schedule)->published_at;
5489
5790
  }
5490
5791
  }
5491
5792
  ```
@@ -5549,6 +5850,58 @@ export interface ManifestAssembled {
5549
5850
 
5550
5851
  [Building the Array in a Variable](https://tolki.abe.dev/ts/api-resources.html#building-the-array-in-a-variable) on the API Resources page lists the writes the package follows.
5551
5852
 
5853
+ A query chain that starts at a model is typed step by step, as in [page props](https://tolki.abe.dev/ts/routing.html#what-the-props-expression-can-be). `Post::query()->pluck('id')->first()` publishes `number | null`. A model the chain returns is presented as `Partial<Model>`, as a [model property](#model--enum-aware-properties) is, so `User::find($this->userId)` publishes `Partial<User> | null` and `User::query()->where('id', 1)->get()` publishes `Partial<User>[]`.
5854
+
5855
+ An `EnumResource` around an enum that may be `null` adds `| never[]`, and so does each element of a `map()` of such wraps, because an event sends the empty resource as `[]`.
5856
+
5857
+ #### `when()` and `unless()` From `Conditionable`
5858
+
5859
+ An event that uses Laravel's `Conditionable` trait can call `$this->when()` and `$this->unless()` in `broadcastWith()`. Unlike a resource's `when()`, they always send the key: the callback's value when the condition holds, the default's when it doesn't, and the event itself where either one returns `null` or no default is passed. The key publishes that union, required:
5860
+
5861
+ ```php
5862
+ class PostPinned implements ShouldBroadcast
5863
+ {
5864
+ use Conditionable;
5865
+
5866
+ public function __construct(public Post $post) {}
5867
+
5868
+ public function broadcastWith(): array
5869
+ {
5870
+ $pinned = $this->post->is_pinned;
5871
+
5872
+ return [
5873
+ 'label' => $this->when($pinned, fn () => 'active'),
5874
+ 'with_default' => $this->when(
5875
+ $pinned,
5876
+ fn () => 'pinned',
5877
+ fn () => 'unpinned',
5878
+ ),
5879
+ ];
5880
+ }
5881
+
5882
+ public function broadcastOn(): Channel
5883
+ {
5884
+ return new Channel('posts');
5885
+ }
5886
+ }
5887
+ ```
5888
+
5889
+ `label` can send the event itself, whose JSON is its public `post` property:
5890
+
5891
+ ```typescript
5892
+ import type { Post } from "../models";
5893
+
5894
+ /** @see App\Events\PostPinned */
5895
+ export interface PostPinned {
5896
+ label: string | { post: Post };
5897
+ with_default: string;
5898
+ }
5899
+ ```
5900
+
5901
+ The event's own JSON joins the type only when the package knows it. An event `make:event` generates uses `InteractsWithSockets`, whose untyped `$socket` property leaves that JSON unknown, so a key that can send such an event publishes `unknown`. Pass a default that returns a value, as `with_default` does, or type the key with [`#[TsCasts]`](#overriding-property-types-with-tscasts).
5902
+
5903
+ A resource built around the call, such as `UserResource::make($this->when(…))`, is always sent too, so it publishes required.
5904
+
5552
5905
  ### Model & Enum-Aware Properties
5553
5906
 
5554
5907
  A property typed as an Eloquent model or a PHP enum resolves to the type the rest of the package uses for it. The file imports that type for you:
@@ -5964,11 +6317,11 @@ class UserResource extends JsonResource
5964
6317
  }
5965
6318
  ```
5966
6319
 
5967
- Inside another resource, `EnumResource::make($this->status)` and `new EnumResource($this->status)` both publish the property as `AsEnum<typeof Status>`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource) on the API Resources page.
6320
+ Inside another resource, `EnumResource::make($this->status)` and `new EnumResource($this->status)` both publish the property as `AsEnum<typeof Status>`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource) on the API Resources page. A bare value sends no object: `'status' => Status::Published->value` publishes that case's own value, `1`. [Reading `->value` and `->name`](https://tolki.abe.dev/ts/enums.html#reading-value-and-name) covers bare values and `cases()`.
5968
6321
 
5969
- The same rewrite applies to [Inertia shared data](https://tolki.abe.dev/ts/inertia.html). With `enums.use_tolki_package` on (the default), an `EnumResource::make()` returned from your middleware's `share()` publishes as `AsEnum<typeof Role>` in `inertia-config.d.ts`, with `import { type AsEnum } from '@tolki/ts'` and an import of the `Role` const above the declarations. A shared key whose ternary picks between two different enums isn't rewritten. It publishes as `RoleType | StatusType` with neither enum imported, so TypeScript reports both names as missing (`TS2304`). Give both arms the same enum. See the `EnumResource` note in [How the Augmentation File Is Generated](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated).
6322
+ The same rewrite applies to [Inertia shared data](https://tolki.abe.dev/ts/inertia.html). With `enums.use_tolki_package` on (the default), an `EnumResource::make()` returned from your middleware's `share()` publishes as `AsEnum<typeof Role>` in `inertia-config.d.ts`, with `import { type AsEnum } from '@tolki/ts'` and an import of the `Role` const above the declarations. Route page props are rewritten the same way. See the `EnumResource` notes in [How the Augmentation File Is Generated](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated).
5970
6323
 
5971
- `EnumResource` turns off Laravel's resource wrapping (`public static $wrap = ''`), so the response is the flat object shown below, not wrapped in a `data` key. When the enum is `null`, the resource returns `null` instead of an object.
6324
+ `EnumResource` turns off Laravel's resource wrapping (`public static $wrap = ''`), so the response is the flat object shown below, not wrapped in a `data` key. When the enum is `null`, the resource returns `null` instead of an object. As an Inertia page prop or shared value, Inertia sends `[]` instead, so the prop publishes `AsEnum<typeof Status> | never[]`. A broadcast event's payload, and a `map()` of wraps kept as a collection inside another resource, send `[]` too, and publish `| never[]`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource).
5972
6325
 
5973
6326
  ### Response Shape
5974
6327
 
@@ -6277,6 +6630,8 @@ export const ExcludableEnum = defineEnum({
6277
6630
 
6278
6631
  export type ExcludableEnumType = "alpha" | "beta";
6279
6632
  export type ExcludableEnumKind = "Alpha" | "Beta";
6633
+
6634
+ export type ExcludableEnum = ExcludableEnumType;
6280
6635
  ```
6281
6636
 
6282
6637
  `overridden()` and `overriddenStatic()` have attributes that would include them whatever the auto-include settings, but `#[TsExclude]` removes them. `label()` and `secret()` are missing because auto-include is off. Turn on `enums.auto_include_methods`, and `label()` publishes while `secret()` stays out. See [Auto-Including All Enum Methods](https://tolki.abe.dev/ts/enums.html#auto-including-all-enum-methods) for which methods auto-include adds.
@@ -7225,17 +7580,19 @@ This page covers shared data, and the API resources that shared data and a route
7225
7580
  With `inertia.enabled` on (the default), the package builds the file from your middleware:
7226
7581
 
7227
7582
  - **Finding the middleware**: the package searches `inertia.inertia_middleware_path`, or `app_path()` when that isn't set, for a class that extends `Inertia\Middleware`. If it finds none, it writes no file. If your app has more than one such class, point `inertia.inertia_middleware_path` at the directory that holds the one you want.
7228
- - **Reading `share()`**: every key's value is typed from your code, without handling a real request. A `share()` that a trait supplies is read too, and so is one that builds its array in a variable and returns it. A key that the variable gets on only some paths, such as inside an `if`, is optional.
7229
- - **Parent middleware**: a `...parent::share($request)` spread and `array_merge(parent::share($request), [...])` are both read, all the way up your middleware's parent classes. A later key overrides an earlier one and keeps the earlier one's position, as PHP does.
7583
+ - **Reading `share()`**: every key's value is typed from your code, without handling a real request. A `share()` that a trait supplies is read too, even under an alias such as `use SharesProps { base as share; }`, and so is one that builds its array in a variable and returns it. A key that the variable gets on only some paths, such as inside an `if`, is optional.
7584
+ - **Parent middleware**: a `...parent::share($request)` spread and `array_merge(parent::share($request), [...])` are both read, all the way up your middleware's parent classes. A later key overrides an earlier one and keeps the earlier one's position, as PHP does. A parent's `#[TsCasts]` applies too, as [Type Resolution Priority](#type-resolution-priority) describes.
7585
+ - **Dotted keys**: Inertia unpacks a top-level dotted key into nested objects, so `'auth.name' => $request->user()?->name` publishes `auth: { name: string | null }`. When the array also holds an `auth` array, `name` is added to it.
7230
7586
  - **Integer keys**: Inertia merges shared data and page props with `array_merge()`, which renumbers integer keys from `0`. A top-level `42 => …` key therefore publishes as `"0"`, and `ts:publish` warns that you probably meant a string key. Nested keys keep theirs.
7231
- - **`$request->user()`**: typed through your live auth config, from `auth.defaults.guard` to that guard's provider to the provider's `model`. The prop becomes `User | null`, and the file imports the model's type for you. `auth()->user()`, `auth()->id()`, `Auth::user()` and `Auth::id()` resolve the same way.
7587
+ - **The signed-in user**: `$request->user()` is typed through your live auth config, from `auth.defaults.guard` to that guard's provider to the provider's `model`. The prop becomes `User | null`, and the file imports the model's type for you. `auth()->user()`, `Auth::user()`, `request()->user()` and `Auth::guard()->user()` resolve the same way, and so does a read past any of them, such as `auth()->user()?->name`, which publishes `string | null`. `auth()->id()` and `Auth::id()` publish the user's key, as described below.
7232
7588
  - **Request helpers**: `$request->url()`, `fullUrl()`, `path()`, `integer()`, `boolean()`, `string()`, `cookie()` and `hasCookie()` are typed from Laravel's own signatures.
7233
7589
  - **`config()`**: `config('some.key')` with a literal key is typed from the live config value, since the package runs inside your booted app. A computed key stays `unknown`.
7234
7590
  - **Value helpers**: `now()` and `today()` are typed as `string`, or `Date` under [`timestamps_as_date`](https://tolki.abe.dev/ts/models.html#timestamps-as-date-objects). `str($value)` is typed as `string`, and `str()` with no argument as `Record<string, never>`. `url($path)` is typed as `string` when the path can't be `null`, and stays `unknown` when it can or has no type. `collect([...])` and a bare array literal are both typed as the list or object the array encodes as, such as `string[]` for `['a', 'b']`. `+` on two arrays is typed as PHP's array union, where the left side's keys win.
7235
- - **Closures and first-class callables**: Inertia calls a callable prop before it sends it, so closures and first-class callables, such as `fn () => $request->url()` and `now(...)`, are typed from what the call returns.
7236
- - **Inertia v2 prop wrappers**: `Inertia::defer()`, `optional()`, `lazy()`, `always()`, `merge()` and `deepMerge()` type as the value they wrap. The three a partial reload can leave out, `defer`, `optional` and `lazy`, make the key optional.
7591
+ - **Closures and first-class callables**: Inertia calls a callable prop before it sends it, so closures and first-class callables, such as `fn () => $request->url()` and `now(...)`, are typed from what the call returns. That includes one inside an array that a helper method builds.
7592
+ - **Inertia v2 prop wrappers**: `Inertia::defer()`, `optional()`, `lazy()`, `always()`, `merge()` and `deepMerge()` type as the value they wrap, and so does a prop class you construct, such as `new OptionalProp(fn () => …)`. The three a partial reload can leave out, `defer`, `optional` and `lazy`, make the key optional.
7237
7593
  - **API resources**: a resource or resource collection is typed as the response Inertia sends for it, as [API Resources in Props](#api-resources-in-props) describes.
7238
7594
  - **`EnumResource` props**: a prop that wraps an enum in `EnumResource`, such as `'role' => EnumResource::make(Role::Admin)`, becomes `AsEnum<typeof Role>` when `enums.use_tolki_package` is on (the default), the same as in [API Resources](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource). With it off, the key keeps the enum's type alias (`role: RoleType`). The change applies per key, so another key that reads the enum directly keeps `RoleType`.
7595
+ - **`EnumResource` ternaries and `null`**: each arm of a ternary is typed as Laravel sends it. Wrapping two different enums publishes `AsEnum<typeof Role> | AsEnum<typeof Status>`, and a wrap beside a bare case of the same enum publishes `AsEnum<typeof Status> | StatusType`. A wrap around an enum that may be `null` publishes `AsEnum<typeof Status> | never[]`, because Inertia sends `[]` for it, not `null`. Tell the two apart with `Array.isArray()`.
7239
7596
  - **Enum cases**: a bare case, such as `'defaultStatus' => Status::Draft`, is typed as the enum's type alias (`defaultStatus: StatusType`), which matches the value Laravel sends for a backed enum. The file imports the alias for you.
7240
7597
  - **Classes with `#[TsType]`**: a value of a class that has or inherits a `#[TsType]` is typed as that type, with its import, in shared data and page props alike. See [Custom Types](https://tolki.abe.dev/ts/custom-types.html).
7241
7598
  - **`errors`**: left out. `@inertiajs/core` already types `page.props.errors` as `Errors & ErrorBag`, and [`errorValueType`](#anatomy-of-the-generated-file) sharpens it. A `#[TsCasts]` or `@return` docblock entry named `errors` still adds one if you want it.
@@ -7245,9 +7602,11 @@ With `inertia.enabled` on (the default), the package builds the file from your m
7245
7602
 
7246
7603
  When the package can't create an instance of the model, it reads the key type from the class, and publishes `unknown` if code works the key out. A `getAuthIdentifierName()` that works the column out in code, such as from config, publishes `unknown` too, and so does an override of `getAuthIdentifier()`, since only running your app shows which value the ID holds.
7247
7604
 
7605
+ The signed-in user is typed from the default guard only, so a named guard, such as `auth('admin')->user()` or `Auth::guard('admin')->user()`, publishes `unknown`. When your guards' providers name more than one user model, a route's guard middleware can sign in either one, so `request()->user()`, `Auth::guard()->user()` and a read past `auth()->user()`, `Auth::user()` or `request()->user()` publish `unknown` too. `$request->user()`, a bare `auth()->user()` or `Auth::user()`, `auth()->id()` and `Auth::id()` keep the default guard's model. Type such a key with [`#[TsCasts]`](#type-resolution-priority).
7606
+
7248
7607
  In a route's [page props](https://tolki.abe.dev/ts/routing.html#inertia-integration), `getKey()` on a route-bound model publishes the model's key type with no `| null`, because Laravel binds only a saved row. With a `Post $post` action parameter, `'post_id' => $post->getKey()` publishes `post_id: number`. A relation read on the parameter is typed by the models it loads, so `'comments' => $post->comments` publishes `comments: Comment[]`.
7249
7608
 
7250
- A key whose ternary arms wrap different enums, such as `$cond ? EnumResource::make(Role::Admin) : EnumResource::make(Status::Draft)`, renders as `RoleType | StatusType` with no import for either name. Your build then fails with a `TS2304` error for each. Give both arms the same enum, or override that key with a `#[TsCasts]` entry that has an `import`.
7609
+ A few mixes of `EnumResource` arms publish a type that doesn't match what Laravel sends. A wrap beside a bare case of another enum, as in `$cond ? EnumResource::make(Role::Admin) : Status::Draft`, publishes `RoleType | StatusType`, though the first arm sends the `Role` object. A nested ternary over the wraps of three enums can leave a type alias unimported, which fails your build with `TS2304`. Override such a key with a `#[TsCasts]` entry that has an `import`.
7251
7610
 
7252
7611
  ### Anatomy of the Generated File
7253
7612
 
@@ -7304,13 +7663,13 @@ export {};
7304
7663
 
7305
7664
  Each part of the file does one job:
7306
7665
 
7307
- - **`import type { User } from "./app/models";`**: every model, resource or enum that a prop type names gets an import at the top, with a path relative to the output root. An `EnumResource` prop is the exception under the default `enums.use_tolki_package`. It renders as `AsEnum<typeof Role>`, so the enum's const is imported as a value (`import { Role } from './app/enums';`), under an `import { type AsEnum } from '@tolki/ts';` line, and both come before the `import type` lines. Imports from an `import` key in `#[TsCasts]` join the `import type` lines.
7666
+ - **`import type { User } from "./app/models";`**: every model, resource or enum that a prop type names gets an import at the top, with a path relative to the output root. An `EnumResource` prop is the exception under the default `enums.use_tolki_package`. It renders as `AsEnum<typeof Role>`, so the enum's const is imported as a value (`import { Role } from './app/enums';`), under an `import { type AsEnum } from '@tolki/ts';` line, and both come before the `import type` lines. Imports from an `import` key in `#[TsCasts]` join the `import type` lines. Two classes that share a name, such as `App\Enums\Status` and `App\Crm\Enums\Status`, are imported under aliases, as in `StatusType as CrmStatusType`.
7308
7667
  - **`declare global { namespace Inertia { type SharedData = ...; } }`**: makes `Inertia.SharedData` available by name in any `.ts` file in your project. That includes the generated route files, which combine it with each page's props, as [Inertia Integration](https://tolki.abe.dev/ts/routing.html#inertia-integration) shows.
7309
7668
  - **`declare module '@inertiajs/core' { ... }`**: augments Inertia's own `InertiaConfig`, so `usePage().props` is typed across your frontend without you writing the augmentation.
7310
7669
  - **`errorValueType: string[]`**: added only when the middleware sets `protected $withAllErrors = true;`. It matches the shape Inertia uses for its validation errors in that mode.
7311
7670
  - **`export {};`**: TypeScript accepts a `declare global` block only in a module, a file with at least one top-level `import` or `export`. This line makes the file a module even when it has no imports.
7312
7671
 
7313
- The file imports only the names its types use. A key you override with `#[TsCasts]` drops the import its inferred type needed.
7672
+ The file imports only the names its types use. A key you override with `#[TsCasts]` drops the imports its inferred type needed, but keeps the import of a class the override names and the key's value holds. `'owner' => 'User | null'` over `$request->user()` still imports `User`, with no `import` key.
7314
7673
 
7315
7674
  A key that isn't a plain identifier, such as `'can-edit'` or `42`, is quoted, as in `"can-edit": boolean`. Route files quote a page prop's key the same way.
7316
7675
 
@@ -7320,8 +7679,8 @@ A value the package can't read stays `unknown`. `'flash' => ['success' => fn ()
7320
7679
 
7321
7680
  Each key from `share()` takes its type from the first of these that covers it:
7322
7681
 
7323
- 1. **`#[TsCasts]`** on the middleware class or on its `share()` method. When both name a key, the method's entry wins, even when the two spell an index signature's name differently. It's the same attribute [models](https://tolki.abe.dev/ts/models.html#tscasts), [API resources](https://tolki.abe.dev/ts/api-resources.html#overriding-property-types-with-tscasts) and [broadcast events](https://tolki.abe.dev/ts/broadcast-events.html#overriding-property-types-with-tscasts) use.
7324
- 2. **A `@return array{...}` docblock** on `share()`. You write the shape by hand, for a key the package can't infer, such as a method call whose return type says nothing. A `key?:` entry makes that key optional.
7682
+ 1. **`#[TsCasts]`** on the middleware class or on its `share()` method. When both name a key, the method's entry wins, even when the two spell an index signature's name differently. A parent middleware's entries apply too when your middleware inherits the parent's `share()` or reads it through `parent::share()`, and your class's entries win over the parent's. It's the same attribute [models](https://tolki.abe.dev/ts/models.html#tscasts), [API resources](https://tolki.abe.dev/ts/api-resources.html#overriding-property-types-with-tscasts) and [broadcast events](https://tolki.abe.dev/ts/broadcast-events.html#overriding-property-types-with-tscasts) use.
7683
+ 2. **A `@return array{...}` docblock** on `share()`. You write the shape by hand, for a key the package can't infer, such as a method call whose return type says nothing. A `key?:` entry makes that key optional. A model or enum that a top-level key names, as in `owner: User`, is imported for you.
7325
7684
  3. **Inference from your code**, the default. It covers plain values, nested arrays, conditionals, closures, spreads, `array_merge()`, `config()`, the request and auth helpers, and Inertia's prop wrappers.
7326
7685
 
7327
7686
  A key that `#[TsCasts]` or the docblock names but `share()` doesn't return is added to the type.
@@ -7354,7 +7713,7 @@ Here `appName` takes its type from `#[TsCasts]` and `flash` takes its type from
7354
7713
 
7355
7714
  ### API Resources in Props
7356
7715
 
7357
- Inertia sends an API resource prop as the resource's whole response, the same JSON a route that returns the resource sends. That holds at any depth of a route's page props and in `share()`, so each prop publishes that response:
7716
+ Inertia sends an API resource prop as the resource's whole response, the same JSON a route that returns the resource sends. That holds at any depth of a route's page props and in `share()`, including props that a helper method or another class's method builds, as in `Inertia::render('Posts/Show', $this->props->build())`. Each prop publishes that response:
7358
7717
 
7359
7718
  ```php
7360
7719
  return Inertia::render('Posts/Show', [
@@ -7380,10 +7739,34 @@ Each kind of prop follows its own rule:
7380
7739
  - **`Resource::collection()`** publishes `AnonymousResourceCollection<CommentResource>` from `@tolki/types`, which is `{ data: CommentResource[] }`.
7381
7740
  - **A named collection** publishes its own interface, which already holds its wrap key. One whose `toArray()` returns no wrap key publishes `{ data: TagCollection }`, because Laravel nests that body under `data`.
7382
7741
  - **`->toResourceCollection()`** with no argument publishes the collection Laravel guesses. Over an empty collection, Laravel skips the guess and sends `{ data: [] }`, so the prop also publishes that empty response, such as `UserCollection | { data: never[] }` or, over `paginate()`, `| JsonResourcePaginator<never>`. A guessed collection whose response is only its `data` list already fits it and gets no extra type.
7742
+ - **Keys beside `data`**: the keys that a resource's `with()` method or an `->additional([...])` call adds are published beside the body. A single resource merges them into its object, as in `{ data: PostResource; meta: { total: number } }`, and any other response is intersected with them, as in `AnonymousResourceCollection<CommentResource> & { meta: { total: number } }`. A `with()` key that a `when()` call may leave out arrives as `[]`, so it publishes `T | never[]`.
7743
+ - **A resolved resource**, from `->resolve()`, publishes the resource's own type, with no `data` key. Inertia still sends each API resource inside the resolved body as a response, so a key that holds one publishes that response, as the example below shows. `Resource::collection(...)->resolve()` publishes a list of the same.
7383
7744
 
7384
- The wrap key is the one your app sets by the time `ts:publish` runs, as [The Wrap Key Your App Sets](https://tolki.abe.dev/ts/api-resources.html#the-wrap-key-your-app-sets) describes. After `JsonResource::withoutWrapping()`, a single resource publishes the bare `PostResource`, and `Resource::collection()` over items that aren't paginated publishes `CommentResource[]`. Over a paginator, Laravel keeps the `data` key. After `JsonResource::wrap('items')`, a single resource publishes `{ items: PostResource }`.
7745
+ Here `PostCardResource` returns `'author' => UserCardResource::make($this->author)` among its keys:
7385
7746
 
7386
- Some props publish less than Inertia sends. The keys that `additional()` or a resource's `with()` method add beside `data` aren't published, and after `JsonResource::withoutWrapping()` those keys still make Laravel nest the resource under `data`, while the package publishes it bare. `Resource::collection(...)->additional(...)` publishes `unknown`. Props that another class's method builds, as in `Inertia::render('Posts/Show', $this->props->build())`, publish each API resource inside them bare, though Inertia sends it under `data`. Type such a prop with [`#[TsCasts]`](https://tolki.abe.dev/ts/routing.html#overriding-props-with-tscasts).
7747
+ ```php
7748
+ return Inertia::render('Posts/Show', [
7749
+ 'post' => PostResource::make($post)->additional([
7750
+ 'meta' => ['total' => $post->comments()->count()],
7751
+ ]),
7752
+ 'card' => PostCardResource::make($post)->resolve(),
7753
+ ]);
7754
+ ```
7755
+
7756
+ Both props publish what Inertia sends:
7757
+
7758
+ ```typescript
7759
+ export type ShowPageProps = Inertia.SharedData & {
7760
+ post: { data: PostResource; meta: { total: number } };
7761
+ card: Omit<PostCardResource, "author"> & {
7762
+ author: { data: UserCardResource };
7763
+ };
7764
+ };
7765
+ ```
7766
+
7767
+ After `->resolve()`, a resource collection class with its own `toArray()` publishes its items bare, though Inertia sends each one under `data`. Pass the collection itself, or type the prop with [`#[TsCasts]`](https://tolki.abe.dev/ts/routing.html#overriding-props-with-tscasts).
7768
+
7769
+ The wrap key is the one your app sets by the time `ts:publish` runs, as [The Wrap Key Your App Sets](https://tolki.abe.dev/ts/api-resources.html#the-wrap-key-your-app-sets) describes. After `JsonResource::withoutWrapping()`, a single resource publishes the bare `PostResource`, and `Resource::collection()` over items that aren't paginated publishes `CommentResource[]`. Over a paginator, Laravel keeps the `data` key. Keys from `with()` or `additional()` also make Laravel nest the resource under `data`, and the prop publishes it that way. After `JsonResource::wrap('items')`, a single resource publishes `{ items: PostResource }`.
7387
7770
 
7388
7771
  #### JSON:API Resources in Props
7389
7772
 
@@ -7458,7 +7841,7 @@ export type IndexPageProps = Inertia.SharedData & {
7458
7841
  };
7459
7842
  ```
7460
7843
 
7461
- `paginate()`, `simplePaginate()`, and `cursorPaginate()` are all recognized, in the `new SomeCollection(...)`, `SomeResource::collection(...)`, and `->toResourceCollection()` forms.
7844
+ `paginate()`, `simplePaginate()`, and `cursorPaginate()` are all recognized, in the `new SomeCollection(...)`, `SomeResource::collection(...)`, and `->toResourceCollection()` forms. The paginator can also come from a query builder held in a variable, or from a controller method or an injected service's method, typed from the method's return type or its body. A call that hands back the same paginator, such as `withQueryString()`, `appends()` or `onEachSide()`, keeps its kind.
7462
7845
 
7463
7846
  Each paginator sends its own `meta` block, so each gets its own type from `@tolki/types`. A named collection adds the pagination type to its own interface. An anonymous collection, from `SomeResource::collection(...)`, publishes the paginator's whole response, and so does a collection with `$wrap = null`, because Laravel sends it under `data` over a paginator. In this list, the named form comes first, and `R` is the collected resource:
7464
7847
 
@@ -7468,17 +7851,16 @@ Each paginator sends its own `meta` block, so each gets its own type from `@tolk
7468
7851
 
7469
7852
  A prop that can hold more than one paginator kind, such as a ternary over `paginate()` and `simplePaginate()`, publishes `TeamCollection & (ResourceSimplePagination | ResourcePagination)`. One that can hold a plain collection or a paginator publishes both shapes, `TeamCollection | (TeamCollection & ResourcePagination)`. A collection that `share()` returns is typed the same way.
7470
7853
 
7471
- When the package doesn't see a paginator, the prop doesn't lose its type. It gets the collection's type without the pagination part, which is wrong rather than missing. The package sees a paginator that a query chain starting at the model returns, such as `Post::query()->simplePaginate(10)`, or one held in a local variable assigned that way. It doesn't follow a paginator from a query builder held in a variable, from a controller method such as `$this->page()`, or from a method of an injected service:
7854
+ When the package can't tell which paginator a payload holds, the prop gets the collection's type without the pagination part, a wrong type rather than a missing one. That happens with a method declared to return the `Paginator` contract, which more than one paginator kind implements, or with one that has no return type and a body the package can't read:
7472
7855
 
7473
7856
  ```php
7474
- $q = Post::query();
7475
-
7857
+ // page() is declared to return the Paginator contract
7476
7858
  return Inertia::render('Posts/Index', [
7477
- 'posts' => new PostCollection($q->paginate(10)), // not detected
7859
+ 'posts' => new PostCollection($this->posts->page()),
7478
7860
  ]);
7479
7861
  ```
7480
7862
 
7481
- Here `posts` types as `PostCollection`, without `& ResourcePagination`, and the same paginator passed without a resource publishes `unknown`. Build the paginator in the props, or type the prop with [`#[TsCasts]`](https://tolki.abe.dev/ts/routing.html#overriding-props-with-tscasts).
7863
+ Here `posts` types as `PostCollection`, without `& ResourcePagination`. A paginator passed without a resource is typed only from a query chain that starts at a model, or from a method that returns one. From a query builder held in a variable, it publishes `unknown`. Declare the paginator class the method returns, such as `LengthAwarePaginator`, build the paginator in the props, or type the prop with [`#[TsCasts]`](https://tolki.abe.dev/ts/routing.html#overriding-props-with-tscasts).
7482
7864
 
7483
7865
  ### Output Location
7484
7866
 
@@ -8189,11 +8571,12 @@ The package reads the props argument as an expression, not only as an array lite
8189
8571
  public function show(Post $post, Request $request): Response
8190
8572
  {
8191
8573
  return Inertia::render('Posts/Show', [
8192
- 'post' => $post,
8574
+ 'post' => $post->load('author:id,name'),
8193
8575
  'comments' => Comment::query()->latest()->get(),
8194
8576
  'author' => $request->user(),
8577
+ 'viewer' => auth()->user()?->name,
8195
8578
  'page' => $request->integer('page'),
8196
- 'related' => Post::query()->paginate(10),
8579
+ 'related' => Post::query()->paginate(10)->withQueryString(),
8197
8580
  'tally' => Inertia::defer(fn () => Comment::query()->count()),
8198
8581
  ]);
8199
8582
  }
@@ -8203,32 +8586,54 @@ This generates:
8203
8586
 
8204
8587
  ```typescript
8205
8588
  export type ShowPageProps = Inertia.SharedData & {
8206
- post: Post;
8589
+ post: Post & { author: Pick<User, "id" | "name"> };
8207
8590
  comments: Comment[];
8208
8591
  author: User | null;
8592
+ viewer: string | null;
8209
8593
  page: number;
8210
8594
  related: LengthAwarePaginator<Post>;
8211
8595
  tally?: number;
8212
8596
  };
8213
8597
  ```
8214
8598
 
8215
- These expressions are typed:
8599
+ Eloquent finders and collections are typed step by step from the model the chain starts at:
8216
8600
 
8217
- - **Eloquent finders and collections**, typed from the model the chain starts at. `find()`, `first()` and `firstWhere()` are `Model | null`. `findOrFail()`, `firstOrFail()`, `sole()`, `create()`, `make()`, `firstOrCreate()`, `firstOrNew()` and `updateOrCreate()` are `Model`. `all()` and `get()` are `Model[]`. `paginate()`, `simplePaginate()` and `cursorPaginate()` are `LengthAwarePaginator<Model>`, `SimplePaginator<Model>` and `CursorPaginator<Model>`, imported from `@tolki/types`. `count()` is `number` and `exists()` is `boolean`.
8601
+ | Call | Type |
8602
+ | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
8603
+ | `find()`, `first()`, `firstWhere()` | `Model \| null` |
8604
+ | `findOrFail()`, `firstOrFail()`, `sole()`, `create()`, `make()`, `firstOrCreate()`, `firstOrNew()`, `updateOrCreate()` | `Model` |
8605
+ | `all()`, `get()`, `cursor()`, `findMany()`, and `find()` with a list of keys | `Model[]` |
8606
+ | `pluck('title')` | A list of the column's type |
8607
+ | `value('title')` | The column's type, or `null` |
8608
+ | `count()` | `number` |
8609
+ | `exists()` | `boolean` |
8610
+
8611
+ A relation step moves the chain to the related model, so `Post::find(1)->comments()->get()` is `Comment[]`. A read past a finder is typed too, so `Post::find(1)?->title` is `string | null`.
8612
+
8613
+ These expressions are typed too:
8614
+
8615
+ - **Paginators**: `paginate()`, `simplePaginate()` and `cursorPaginate()` are `LengthAwarePaginator<Model>`, `SimplePaginator<Model>` and `CursorPaginator<Model>`, imported from `@tolki/types`. A call that hands back the same paginator, such as `withQueryString()` or `appends()`, keeps that type, and `through()` types the items as its callback returns them.
8218
8616
  - **Route-bound model parameters**: a `Post $post` parameter is `Post` wherever a prop uses it, and a relation read on it is typed by the models the relation loads, so `$post->author` is `User` and `$post->comments` is `Comment[]`.
8219
- - **PHP enums**: a prop holding an enum is the enum's `{Name}Type` alias, imported from the generated [enums](https://tolki.abe.dev/ts/enums.html). That includes a bare case, such as `'status' => Status::Active`. A rename with [`#[TsEnum]`](https://tolki.abe.dev/ts/enums.html#tsenum) carries over, so `#[TsEnum(name: 'Size')] enum ShirtSize` gives you `size: SizeType`.
8220
- - **`$request->user()`**, typed through your `auth` config the same way [shared data](https://tolki.abe.dev/ts/inertia.html) is, and the typed `Request` reads such as `integer()`, `boolean()`, `string()` and `url()`.
8617
+ - **`load()` and `loadMissing()`**: the model with the relations the call loads, such as `Post & { author: User }`, or a list of that on a collection. A column list publishes a `Pick`, as the example shows, and a dotted path nests, so `load('author.posts')` is `Post & { author: User & { posts: Post[] } }`. A to-one relation adds `| null` where a closure may filter it out, or where a column list leaves out the key Laravel matches it by. Only the value the call returns carries the relations, so call `load()` inside the prop: `$post->load('author');` on its own line, followed by `'post' => $post`, publishes `Post`.
8618
+ - **PHP enums**: a prop holding an enum is the enum's `{Name}Type` alias, imported from the generated [enums](https://tolki.abe.dev/ts/enums.html). That includes a bare case, such as `'status' => Status::Active`. A rename with [`#[TsEnum]`](https://tolki.abe.dev/ts/enums.html#tsenum) carries over, so `#[TsEnum(name: 'Size')] enum ShirtSize` gives you `size: SizeType`. Two enums with the same class name in different namespaces are imported under aliases, such as `StatusType as CrmStatusType`. An `EnumResource` prop publishes `AsEnum<typeof Status>`, as it does in [shared data](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated).
8619
+ - **The signed-in user**: `$request->user()`, `auth()->user()`, `Auth::user()` and `request()->user()`, and reads past them such as `auth()->user()?->name`, typed through your `auth` config the same way [shared data](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated) is. A named guard, or guards that name more than one user model, can leave some of these `unknown`, as that page describes. `Request` reads such as `integer()`, `boolean()`, `string()` and `url()` are typed too.
8221
8620
  - **`compact()` and `array_merge()`**: passed as the whole props argument, as in `Inertia::render('Posts/Show', compact('post', 'comments'))` or `array_merge($base, [...])`, each types the same as the array literal it builds.
8222
- - **Inertia v2 prop wrappers**: `defer()`, `optional()` and `lazy()` type as the value they wrap and make the key optional, since a partial reload can leave it out. `always()`, `merge()` and `deepMerge()` type as the value they wrap.
8223
- - **API resources and resource collections**, typed as the response Inertia sends for each, such as `{ data: PostResource }` for a single resource and `JsonResourceSimplePaginator<PostResource>` over `simplePaginate()`, including a `#[PreserveKeys]` collection's keyed `data` member. See [API Resources in Props](https://tolki.abe.dev/ts/inertia.html#api-resources-in-props).
8224
- - **A props array assigned from a ternary**, or props built whole by a method on an injected service, as in `Inertia::render('Posts/Show', $this->service->build())`.
8225
- - **Closures and first-class callables**: Inertia calls a callable prop, so `fn () => $this->label()` and `$this->label(...)` are both typed from what the call returns. In props that another class's method or a controller helper method builds, a first-class callable publishes `Record<string, never>` and `ts:publish` warns, even though Inertia does call it. Use a closure there.
8621
+ - **Inertia v2 prop wrappers**: `defer()`, `optional()` and `lazy()` type as the value they wrap and make the key optional, since a partial reload can leave it out. `always()`, `merge()` and `deepMerge()` type as the value they wrap. A prop class you construct, such as `new OptionalProp(fn () => …)`, types the same as its factory.
8622
+ - **API resources and resource collections**, typed as the response Inertia sends for each, such as `{ data: PostResource }` for a single resource and `JsonResourceSimplePaginator<PostResource>` over `simplePaginate()`, including a `#[PreserveKeys]` collection's keyed `data` member, the keys `with()` and `additional()` add, and the resources nested in a resource you call `->resolve()` on. See [API Resources in Props](https://tolki.abe.dev/ts/inertia.html#api-resources-in-props).
8623
+ - **A props array in a local variable**, typed from what your code writes to it before the render call. The local can be assigned from a ternary, set one key at a time, assigned in each arm of an `if`, or built with `$base + [...]`. A key written after the render call isn't published, because the call has already copied the array, and keys a loop writes under an interpolated name publish an index signature.
8624
+ - **Props a helper builds**: props built whole by a controller helper method or by a method on an injected service, as in `Inertia::render('Posts/Show', $this->service->build())`, are typed the same way, closures and API resources included.
8625
+ - **Closures and first-class callables**: Inertia calls a callable prop, so `fn () => $this->label()` and `$this->label(...)` are both typed from what the call returns.
8626
+
8627
+ A prop the package can't read is typed `unknown`, and the run carries on. Use [`#[TsCasts]`](#overriding-props-with-tscasts) to set its type. A few shapes the package doesn't follow:
8226
8628
 
8227
- If two enums in different namespaces share a class name, such as `App\Enums\Status` and `App\Billing\Status`, both publish as `StatusType`. A route file whose props use both imports `StatusType` twice, and TypeScript rejects it as a duplicate identifier. Rename one with `#[TsEnum]` to keep them apart.
8629
+ - A props local that a `+=` writes, or one written inside a `switch`, a `try`, or a loop that exits through `continue` or `break`, publishes none of its keys, so the page's type is only `Inertia.SharedData`. Build the props as an array literal instead.
8630
+ - A first-class callable that a constructor stores in a property, as in `$this->stamp = now(...)`, publishes `Record<string, never>`, and `ts:publish` warns, though Inertia calls it and sends what it returns. Set that prop's type with `#[TsCasts]`.
8228
8631
 
8229
- A prop the package can't read is typed `unknown`, and the run carries on. Use [`#[TsCasts]`](#overriding-props-with-tscasts) to set its type.
8632
+ Inertia unpacks a top-level dotted key into nested objects, so `'filters.page' => $request->integer('page')` publishes `filters: { page: number }`. When the props also hold a `filters` array, `page` is added to it.
8230
8633
 
8231
- Inertia merges shared data and page props with `array_merge()`, which renumbers integer keys from `0`. A top-level `42 => …` key therefore publishes as `"0"`, and `ts:publish` warns that you probably meant a string key. Nested keys keep theirs.
8634
+ A page key with the same name as a shared-data key publishes both types intersected, though Inertia sends only the page's value. Give page keys names that shared data doesn't use.
8635
+
8636
+ Inertia merges shared data and page props with `array_merge()`, which renumbers integer keys from `0`. A top-level `42 => …` key therefore publishes as `"0"`, and `ts:publish` warns that you probably meant a string key. A render call that can send one of several arrays, such as the arms of a ternary, numbers each array on its own. Nested keys keep theirs.
8232
8637
 
8233
8638
  Sometimes the package can't analyze an action at all, for example because a class the action depends on fails to load. That route then publishes as a plain helper with no page-props type, and `ts:publish` names the action in a warning after the run. The rest of the run still finishes.
8234
8639
 
@@ -8266,11 +8671,14 @@ export type IndexPageProps = Inertia.SharedData & {
8266
8671
  };
8267
8672
  ```
8268
8673
 
8674
+ An entry with no `import` key that names a class the prop's value holds, such as `'post' => 'Post | null'` over a route-bound `Post`, imports that class for you.
8675
+
8269
8676
  ### Inertia UI Table Props
8270
8677
 
8271
8678
  A route that renders an [Inertia UI Table](https://inertiaui.com/) gets a typed page prop. The package reads the table's model from the table class itself, and never creates the table or calls its `toArray()`:
8272
8679
 
8273
8680
  ```php
8681
+ use App\Models\Post;
8274
8682
  use App\Tables\PostTable;
8275
8683
  use Inertia\Inertia;
8276
8684
 
@@ -8278,6 +8686,7 @@ public function index()
8278
8686
  {
8279
8687
  return Inertia::render('Posts/Index', [
8280
8688
  'posts' => PostTable::make()->defaultSort('-id'),
8689
+ 'total' => Post::query()->count(),
8281
8690
  ]);
8282
8691
  }
8283
8692
  ```
@@ -8290,16 +8699,18 @@ import type { Post } from "../models";
8290
8699
 
8291
8700
  export type IndexPageProps = Inertia.SharedData & {
8292
8701
  posts: TableResource<Post>;
8702
+ total: number;
8293
8703
  };
8294
8704
  ```
8295
8705
 
8706
+ A table is one prop like any other: the render call's other props keep their types, and the action's [`#[TsCasts]`](#overriding-props-with-tscasts) applies. `new PostTable`, a table held in a local variable, one in props a service method builds, and one in [shared data](https://tolki.abe.dev/ts/inertia.html) are typed the same way.
8707
+
8296
8708
  `TableResource` is imported from whichever Inertia UI Table package your `package.json` lists, `@inertiaui/table-vue` or `@inertiaui/table-react`. If neither is listed, the import uses `@inertiaui/table-vue`. To force a package, or to use an alias, set `inertia.ui_table_package` in `config/ts-publish.php`.
8297
8709
 
8298
- The package finds a table's model in any of these places:
8710
+ The package finds a table's model in either of these places:
8299
8711
 
8300
8712
  - A `$resource` property default, as in `protected ?string $resource = Post::class;`.
8301
8713
  - A `query(): Builder` method that returns `Post::query()`, `Post::class`, or a query chain that starts at the model.
8302
- - A service method: when the controller passes `$this->tables->index($request)`, the array that method returns can hold table props.
8303
8714
 
8304
8715
  A table whose model exists only at runtime, for example one set in its constructor, gets no table type. Use [`#[TsCasts]`](#overriding-props-with-tscasts) on the controller method to type its props.
8305
8716
 
@@ -8868,7 +9279,7 @@ To change what `ts:publish` itself does, replace one of its stages instead. See
8868
9279
 
8869
9280
  `analyze()` reads what a method returns: nested arrays, conditionals, closures, and method calls. It works on any class, whether or not it's a resource. A property read or a method call is typed from the class of the value you call it on, such as `$this->author->name` or a local variable. A plain value object gets the same types a resource does for enum `->value` and `->name` reads, `(object)` and `(array)` casts, helpers that return the array you pass them, and an inherited or trait method.
8870
9281
 
8871
- Laravel's conditional methods, such as `$this->when()` and `$this->whenLoaded()`, belong to `JsonResource`, so `analyze()` reads them that way only on a resource. On any other class, `$this->when()` is that class's own method. Laravel's `Conditionable::when()`, which events and other classes can use, returns the callback's result or the object itself. The package doesn't type that, so the key comes back `unknown`, as it does in a publish. A resource built around the call is the exception: `UserResource::make($this->when(…))` still comes back optional on any class, though `Conditionable::when()` always sends the key. Write such a key as a ternary, or give it a `#[TsCasts]` entry on the method with `'optional' => false`.
9282
+ Laravel's conditional methods, such as `$this->when()` and `$this->whenLoaded()`, belong to `JsonResource`, so `analyze()` reads them that way only on a resource. On any other class, `$this->when()` is that class's own method. Laravel's `Conditionable::when()` and `unless()`, which events and other classes can use, return the callback's result, the default's, or the object itself, so the key is always sent. `analyze()` types the key that way, required, as a publish does, and a resource built around the call, such as `UserResource::make($this->when(…))`, comes back required too. See [`when()` and `unless()` From `Conditionable`](https://tolki.abe.dev/ts/broadcast-events.html#when-and-unless-from-conditionable).
8872
9283
 
8873
9284
  This example analyzes a service class's `toPayload()` method:
8874
9285