Upgrade Guide
Upgrading From 2.8
The release after 2.8 follows more of the code in toArray() and its helpers: variables you write more than once or inside a block, closure parameters, instanceof checks, and collection pipelines on any collection. Many values that published unknown now publish their type, and some types gain or lose | null to match what Laravel sends. Run php artisan ts:publish after you update, and check the changes below against your generated files.
null Added or Dropped
transform()closures: Laravel calls the closure only for a filled value, so its parameter no longer holdsnull.$this->transform($this->rating, fn ($rating) => $rating)publishesrating?: string, where it publishedstring | null. The default closure still gets the blank value,nullincluded.- A
when()condition on a variable:$this->when($score, fn () => $score)dropsnullfrom$scorein the value, so it publishesstring, where it publishedstring | null. whenNotNull()with a closure or a first-class callable: a closure is nevernull, so Laravel always sends the key and what the closure returns.$this->whenNotNull(fn () => $this->rating)publishesrating: string | null, where it publishedrating?: string.- A collected
whenLoaded()value: a value that hands a relation the package can't read to a resource'scollection(), such as$this->whenLoaded('branches', CategoryResource::collection(...))over abranches()method that declares no return type, publishesCategoryResource[], where it publishedCategoryResource[] | null. - A resource built inside
map(): a resource built around a relation inside amap()that ends in->all(), or inside an array awhenLoaded()closure returns, adds| null, as in{ profile: ProfileResource | null }[]. It published the bare resource, though Laravel sendsnullthere. See Nullable Relations. - Enum resources in a relation closure or a
map():EnumResource::make()ornew EnumResource()of a nullable enum column inside a relation closure now adds| nullwhere Laravel sendsnull: through->all()or an array, as a resource wrap does. Amap()of enum wraps kept as aCollectionnow publishesX[]where it published(X | null)[]. Laravel sends[]there for anullenum, whichX[]doesn't admit, so end the chain with->all()to get(X | null)[]. - A column read on a new model: a model you build with
newand no attributes reads each column asnull, so(new Post)->titlepublishesstring | null, where it publishedstring. A model you fill, copy or create keeps the column's type. See Method Return Types.
Variables, Branches, and Narrowing
- Variables written more than once: a variable you assign again, in sequence or inside an
if, a loop, atryor acatch, publishes each value that can reach the read, such asstring | number, where it publishedunknown. A variable a reference can write, or one you change with.=,++or another compound assignment, still publishesunknown. A variable assigned inside a block now publishes its type for the reads after it in that block, where it publishedunknown. See Local Variables and Narrowing. - Parameters written inside a block: a closure's or a helper's parameter publishes both the value it was passed and the value a write inside a block assigns, such as
string | number, where it published only the value it was passed. - Returned variables built in branches: each branch of an
ifchain, and each loop, keeps its own value for a key, so a key re-set in anifpublishes both types, such asnumber | string, where it published only its last write's type. A whole new array assigned in one branch replaces the keys only there, so a key that only one side holds publishes optional. See Building the Array in a Variable. - Arrays built in a variable outside
toArray()'s return: a closure in value position, a helper you read as a value, and a local you read as a value now publish the keys their writes set, where they publishedunknownorunknown[]. A merge closure that returns such a variable now merges its keys. +andunset()with a local:return ['id' => $this->id] + $defaults;now publishes the keys of$defaultstoo, andunset($data[$key])now removes the key when$keyis a local holding one string literal.instanceofnarrowing: anifnarrows a variable inside its own block, in anelseiforelsethe earlier tests rule in, and after a guard nested in a loop or anotherif, up to the end of that block. A ternary narrows reads through a$this->propchain in its arm. A resource method that the proven code calls reads the narrowed$this->resource. In a resource collection, anifnarrows the items to the paginator it tests. These reads publishedunknown,null, or every class the variable could hold. See Narrowing Withinstanceof.preg_match()and literal keys:$matchespublishesstring[]when the pattern names no group and the call passes no flags, where it publishedunknown. A literal key read on a variable holding an array shape, such as$row['b'], publishes that key's type.
Collections, Relations, and Query Calls
map()on any collection: amap()callback's parameter holds the collection's element on a local, awhenLoaded()parameter,getRelation(), a query'sget()andcollect()too, with or without a type hint. A class type hint types it whatever the collection holds. Reads through it publishedunknown. A model spread inside the callback, such as[...$comment->toArray(), 'flag' => true], publishes the model the variable holds, where it could name another model or none. See Collection Pipelines.- Keyed collections through a local: after
keyBy(),sortBy(),filter()or another step that breaks the keys, amap()through a local or ending in->all()publishesX[] | Record<string, X>, where it publishedX[]. - Collections passed to a helper: a helper's parameter holds the collection's model, so
$comments->first()?->contentin its body publishesstring | null, where it publishedunknown.only()andexcept()on a variable holding an Eloquent collection publish a list of its models, such asComment[]. - Relation calls the query answers:
$this->comments()->count(),exists(),first()?->content, and other forwarded calls whose query method declares a return type publish it, such asnumberandboolean, where they publishedunknown. An aggregate such asmax(), which declaresmixed, staysunknown. In a model metadata provider,$model instanceof Post ? $model->comments()->count() : nullpublishesnumber | null, where it publishednull. - Relations only a
@returndeclares: a relation method with no native return type whose@returnnames its relation class, such as@return Ancestors<static, static>, now publishes on the model's interface, andwhenLoaded()over it is typed. It was left out. Laravel'sNotifiabletrait declaresreadNotifications()andunreadNotifications()this way, so a notifiable model now publishesread_notifications,unread_notifications, and their_countand_existskeys. - To-many relation subclasses: a relation whose class extends one of Laravel's to-many relations publishes a list such as
Category[], whatever its name. In 2.8 a class name without "Many" published one model. A subclass that loads one model publishesCategory | null. - Route-bound model relations: in page props,
$post->authorpublishesUserand$post->commentsComment[], where they publishedunknown. See What the Props Expression Can Be.
Other Values Now Typed
- String helpers:
Str::upper(),Str::lower()and other Laravel methods whose conditional@returnis a string on every branch publishstring, where they publishedunknown. array_filter(): publishes the array you pass it, with its keys. Over aRecord<string, string>cast it publishesRecord<string, string>. Over a list it publishesstring[] | Record<number, string>where the value is sent as-is, since a gap the filter leaves makes JSON write an object. It publishedunknown.- Integer ranges in docblocks:
int<0, max>,int<1, 10>and other integer ranges in a@returnor@propertytag publishnumber, where they publishedunknown. - A first-class callable in a local:
$label = $this->label(...), passed towhen(),mergeWhen()or another conditional method, publishes what the call returns. - Loop-built keys in an accessor: a model accessor whose getter writes
$totals['k'.$index] = $indexin aforeachpublishes{ [key: `k${string}`]: unknown | undefined }, where it publishedunknown[]. Laravel sends an object, such as{"k1":1,"k2":2}.
Reassigned Values That No Longer Guess
json_decode()of a reassigned parameter: after$title = json_decode($title);, the parameter holds whatjson_decode()returns, soreturn $title;publishesunknown, where it published the parameter's old type, such asstring. Any write that always runs replaces the value a parameter was passed, but a model parameter keeps its model past a write the package can't type. See Typing a Variable With@var.find()on a reassigned closure parameter: after$author = $author->comments->find(1);, reads useComment, so$author?->contentpublishesstring | null, and$author->namepublishesunknown, where it readUser'sname.- A merge closure's own variables: a variable a
merge()closure assigns is its own, so the closure no longer reads the method's variable of the same name. With$label = 'x';intoArray()and$label = $this->id;in the closure, the mergedlabelpublishesnumber, where it publishedstring.
New Warnings
ts:publish now warns after its summary where it left out a value it can't type and only null or an empty array is left. It also warns where a parameter's writes, a returned array's branches, a merge's two sides or a spread helper's returns join and leave a value out. A class the generation cache serves prints none of them, so run php artisan ts:publish --fresh to see every one. See Values Left Out of a Union.
Upgrading From 2.7
Version 2.8 changes what some #[TsCasts] entries publish, and what a merged model publishes. Numeric keys, list literals, enum cases, values built with new, top-level integer keys, casts, and classes with __toString() also now publish as Laravel sends them, and so do API resources and their collections in Inertia props. Some inferred types change too, where the package guessed a type, read the wrong class, or misread a docblock. Update @tolki/ts, run php artisan ts:publish, and check the changes below against your generated files.
Update @tolki/ts
The generated files import types that @tolki/types added in 1.9.0, such as the simple and cursor paginator types and the JSON:API document types. Update @tolki/ts to 1.0.3 or later, which requires that version:
npm install @tolki/ts@latestIf you also install @tolki/types yourself, update it to ^1.9.0.
@tolki/types 1.9.0 types a paginator's from and to as number | null, because Laravel sends null for both on an empty page. Code that uses them as a number needs a null check.
#[TsCasts] Changes
Entries Publish Exactly What You Write
An entry that names an enum's type, over a key that wraps the enum in EnumResource::make(), used to publish the wrap. For example, 'status' => 'StatusType' published AsEnum<typeof Status>. It now publishes StatusType, as written. To keep the wrap, write it in the entry:
#[TsCasts(['status' => 'AsEnum<typeof Status>'])]The Resource's Own Entries Win Over the Model's
An entry on toArray(), or on a method it spreads, now wins over the backing model's entry for the same key, as an entry on the resource class already did. See Overriding Property Types With #[TsCasts] for the full order.
An Entry Without 'optional' Keeps the Key's ?
An entry that leaves out 'optional' now keeps the flag the key gets without the entry, so a key can publish optional where it published required:
- API resources: a resource entry keeps the
?from the model's entry for the same key. - Inertia shared data: an entry keeps the
?from theshare()docblock'skey?:, or, for a key the docblock doesn't name, the?the package infers, such as for a keyshare()returns on only some paths.'optional'also works here now. - Inertia page props: an entry on the controller method keeps the prop's own
?.'optional'also works here now.
To keep such a key required, add 'optional' => false to its entry.
A Merged Model Publishes Its Keys
A merge of $this->resource, passed as it is or returned from a closure, now publishes the keys the model's toArray() writes, each optional behind a condition. See Merge Operations.
Interpolated Keys in Arrays Publish an Index Signature
A key built from literal text around a variable, written straight into the returned array, a merged array or a nested array, now publishes a template-literal index signature. It was left out before. Beside a key the pattern matches but whose type the signature can't take, tsc reports TS2411, and ts:publish warns and names the key. See Interpolated Keys.
Values Publish as Laravel Sends Them
These values now publish what Laravel sends, so some generated types change:
- Numeric keys in API resources: a resource sends an array whose keys are all numeric as a list. A key whose method returns
[1 => 'Basic', 2 => 'Pro']published{ "1": string; "2": string }, and now publishesstring[]. A numeric key beside a named key stays, and a resource with$preserveKeyskeeps every key. See Methods Declared as a Barearray. - Top-level integer keys on a page, shared data, or an event: Inertia merges shared data and page props, and Laravel merges a
broadcastWith()payload, witharray_merge(), which renumbers integer keys from0. A top-level42 => …key therefore publishes as"0"where it published"42", and a numeric#[TsCasts]key there moves the same way.ts:publishwarns that you probably meant a string key. Nested keys keep theirs. - List literals: a bare array literal such as
['a', 'b']publishes the list it encodes as,string[], ascollect([...])does. It publishedRecord<string, unknown>before. A list holding an element the package can't type publishesunknown[]. - Enum cases: a bare case such as
'status' => Status::Activepublishes the enum's type alias,StatusType, in resources, page props, shared data, events, and model metadata. In a model metadata provider, such a case used to stop the run. - Resources built around
null:new UserResource(null)publishesnull, the value Laravel sends, where it publishedUserResource | null. - Values built with
new: a value built in place publishes whatjson_encode()writes, sonew DateTime()publishes the date object andnew RuntimeException('x')publishesRecord<string, never>. Both publishedunknownbefore. See Method Return Types for the values that stayunknown.
Casts and Serialized Classes
These types now follow what Laravel and json_encode() send:
decimal:Ncasts publishstring, because Laravel returns a decimal cast as a string on every database. They publishednumber. An uncastdecimalornumericcolumn now follows the driver you publish on:stringon MySQL, MariaDB and PostgreSQL, andnumberon SQLite and SQL Server. See Numbers.timestampcasts publishnumber, the Unix timestamp Laravel sends, whatevertimestamps_as_dateis set to. They publishedstring, orDate. Atimestampcolumn without that cast, such ascreated_at, keeps its date type. See Dates & Times.- Classes with
__toString()publish their public properties as a shape, orRecord<string, never>when they have none, becausejson_encode()ignores__toString(). They publishedstring. See DTO-Typed Accessors and Casts. - Plain
DateTimevalues: a method or accessor that returns aDateTimeorDateTimeImmutablepublishes{ date: string; timezone_type: number; timezone: string }, the object Laravel sends. It publishedstring. Carbon dates still publishstring. See Method Return Types. - Enum method values publish only what
json_encode()writes, so an object's protected, private and hidden values no longer appear in a published enum. See Object and Array Values.
A custom_ts_mappings entry, #[TsCasts] or #[TsType] still overrides any of these types.
Resource Collections and Props
API resources and their collections now publish the response Laravel sends, so these types change:
- A single resource in props: a page prop or shared value that holds one API resource, from
new,make()ortoResource(), publishes{ data: PostResource }, because Laravel sends it under thedatakey. It publishedPostResource. Read its fields throughdata, such asprops.post.data.title. AfterJsonResource::withoutWrapping(), it publishes the barePostResource. See API Resources in Props. - Paginated resource props: a resource collection over
simplePaginate()orcursorPaginate()publishes that paginator's ownmeta, such asJsonResourceSimplePaginator<PostResource>orPostCollection & ResourceCursorPagination. It published thepaginate()types,JsonResourcePaginator<PostResource>andPostCollection & ResourcePagination, whosemetaholds keys these paginators don't send, such astotal. See Paginating Inline in the Render Call. - Collections after
withoutWrapping(): a named collection with notoArray()of its own, or one whosetoArray()returns the collected list, publishes a type alias of its list, such asexport type PostCollection = PostResource[];. Code that reads itsdatakey no longer compiles, because Laravel doesn't send that key. A collection that sets its own$wrapkeeps it. See The Wrap Key Your App Sets. - Collections Laravel guesses: over an empty collection, an argument-less
toResourceCollection()skips the guess and sends an empty list. When the guessed collection has its owntoArray(), a key publishesUserCollection | never[]and a page prop publishesUserCollection | { data: never[] }, so check for the empty response before you read the collection's own keys. See Nested Resources. - JSON:API resources: a
JsonApiResourcesubclass, from Laravel 12.45, publishes the resource object Laravel sends, withid, atypeliteral,attributes, and optionalrelationships,linksandmeta. As a prop, it publishes the JSON:API document, such asJsonApiDocument<PostResource, UserResource>. See JSON:API Resources.
EnumResource Responses
An EnumResource response now sends an array whose keys are all numeric but don't count up from 0 in order, such as [1 => 'a', 4 => 'b'] or ['01' => 'Jan'], as an object with those keys. That matches the published enum and its AsEnum type. The response used to send such an array as a list. If your frontend relies on the list, wrap the method's array in array_values(). See Object and Array Values.
A method that returns null for a case, or throws, is now sent as null, which matches the published enum. It was sent as an empty string, "". See Response Shape.
Inferred Types That No Longer Guess
These types now follow your code and what Laravel runs, so some generated types change.
Model Keys and Auth IDs
getKey()on a model the package can't inspect: on an abstract model, it publishes the key type the class declares, joined with the key types of its published subclasses, such asnumber | string. On a model whose table the package can't read, such as one whose table doesn't exist yet, it publishes the model's own key type. Both publishedstringthrough$this->resource, andunknownotherwise. Where an abstract model works its key out in code, such as an overriddengetKeyType(), it publishesunknown.modelKeys()on a collection of an abstract model lists the same key type, where it published(string | number)[]. See Method Return Types.getKey()on a model built in place: afternew,replicate(),replicateQuietly()ornewInstance(), it adds| null, such asnumber | null. It was the bare key type.getKey()with anull$primaryKey: publishesnull. It wasnumber.auth()->id()andAuth::id(): for an auth model the package can't inspect, such as one whose table doesn't exist yet or one it can't create an instance of, they publish the model's key type with| null, such asnumber | null. They publishedstring | null. Where code works out the key of a model the package can't create, they publishunknown. An auth model that overridesgetAuthIdentifierName()orgetAuthIdentifier()publishesunknowntoo, where it published its key type with| null. See Inertia.
Reads Through Properties, Helpers, and Variables
- Calls and reads on
$this->prop: a call or a property read on a relation or a property, such as$this->author->commentsCount(), types from the classauthorholds, and$thisinside a relation's closure still means the resource. Before, such a read could use the wrong model, the resource's or the closure's. A method both classes declare now publishes the held class's return type, such asstringwhere it publishednumber. A method or column that only the wrong model declared published a type, where Laravel throws or sendsnull, and now publishesunknown. So does a property read through a to-many relation, such as$this->comments->id, where Laravel throws. $this->resource->m(): publishes what$this->m()does, so a model method declared as a barearraypublishes the shape its body returns. It wasunknown[].- A model's
toArray()as a value:$this->author->toArray()and$this->resource->toArray()publishRecord<string, unknown>, and a relation's collection publishesRecord<string, unknown>[]. They wereunknown[]. On a relation,getCasts()publishesRecord<string, string>, andgetGlobalScopes(),getRelations()andrelationsToArray()publishRecord<string, unknown>, where each publishedunknown[]. - Helper method parameters: a helper's body reads each parameter as its declared type, or as what each call passes when it has none, whether you spread the helper or use its result as a value. A first-class callable passed to
whenLoaded(), such as$this->card(...), gets the loaded relation as its argument. These reads publishedunknown. See Methods Declared as a Barearray. - Helpers spread inside a closure: a spread helper's body no longer reads the closure's parameters or the relation it loads. A helper local named like a closure parameter, as in
fn ($t) => [...$this->ownId()], keeps its own type, such asnumberwhere it publishedstring. A helper parameter reads what the call passes instead of the loaded relation's model, so a column only that model has publishesunknown, where it published that column's type. - An enum or model in a helper's array: when you use the helper's result as a value, that value publishes
unknown, and the rest of the shape keeps its types. The whole array was left untyped before. - Inertia actions and model metadata providers: a typed parameter you read, such as
'id' => $idfromint $id, publishes its type, where it publishedunknown. A nullable model parameter read bare, such as'post' => $postfrom?Post $post = null, publishesPost | null, where it publishedPost. An abstractModel $modelparameter read bare publishesunknown, where it publishedModel, a type no generated file exports. - A reassigned closure or action parameter: once you assign a closure parameter, or an Inertia action's model parameter, a value of another class, the reads after it use that class. They kept using the parameter's model, so a column only that model declares published its type, where it now publishes
unknown. See Typing a Variable With@var. - More kinds of write: a
catch,unset(),staticorglobalnow counts as a write to a local variable. So does a by-reference argument that can change the value's form, such aspreg_match()'s$matches,settype(),sort()on an array that publishes as an object, or one of your own methods. Such a variable publishesunknown, where it published its first value's type. A by-reference built-in that keeps the value's form, such assort()on a list orksort(), keeps the type as before. A copy taken before such a call keeps the type it had. A closure that writes only its own parameter no longer changes an outer variable of the same name. See Local Variables and Narrowing. - Optional keys through
??, a ternary, or a default: a key whose value can be a missing conditional value stays optional, as$this->whenLoaded('author') ?? 'none'and$this->when($flag, $this->whenLoaded('author'), 'none')do. They were required. See Passing a Default Argument.
Docblock Tags
- Docblock tags with spaces: a
@returnor@vartag is read whole, so@return string | nullkeeps its| null. It was cut at the first space. A$resourceproperty tagged@var ?Post, or tagged with a model from the resource's own namespace that the file doesn't import, now finds its backing model. - Docblock shapes:
list{int, string}publishes the tuple[number, string],object{a: int}publishes{ a: number },array<'a'|'b', int>publishes{ a?: number; b?: number }, and quoted keys and a nested?array{...}publish as written. Each was misread or ignored, such aslist{int, string}read asnumber. Acallablein a@returntag or inside a shape publishesunknown, where it published the first type inside it. A local@varaccepts these forms too. See TypingarrayCasts With@property. - A bare class beside its container:
@return User[]|UserpublishesUser[] | User. It wasUser[]. A model enum column typedStatus[]|StatuspublishesAsEnum<typeof Status>[] | AsEnum<typeof Status>in the model's{Model}Resourceinterface, where it publishedAsEnum<typeof Status>[]. @phpstan-typealiases inside a list or a shape:@property list<Row>|nullpublishes a list of the alias's shape, where it publishedunknown[] | null. A promoted constructor property's@varreads an alias too, where it published the property's native type. See Typing JSON Columns With@phpstan-typeAliases.- A nullable
arraycolumn with a nestednull:@property array{a: ?int}on a nullable column publishes{ a: number | null } | null. It was{ a: number | null }.
Generation Cache
The generation cache now rebuilds a class when anything it reads changes, such as an enum method a resource calls, a service, a cast, a value object, a helper function or a #[TsEnum] rename. Editing a published template clears the cache too. You can drop any --fresh you added for these. See When a Class Is Rebuilt.
A run limited by an --only-* flag, such as the one the Vite plugin makes on vite build, now keeps the cache of the features it skips. With the cache on, it also keeps those features in the globals and JSON files, as the last run that published them left them.
If you bind your own globals.writer_class or json.writer_class, $runner->enumGenerators and its siblings hold only the features a partial run published. Join each with its retained list to keep the rest, such as $runner->enumGenerators->concat($runner->retainedEnumGenerators), and do the same for models, resources, form requests and broadcast events.
The first run after you update rebuilds the whole cache, as it does after any package update.
Published Templates
If you published the package's templates, check these:
resource: needs no change. A resource file now importsAsEnumfrom@tolki/tsonly when one of its types uses it, and a published copy does the same.broadcast-eventandglobals: a copy published before this release prints an event's index signature as a quoted property name instead of a signature. Merge the package's new templates into your copies, as Publishing and Editing Templates describes.
Custom Inertia Analyzers
If your app binds its own subclass of InertiaPageAnalyzer or InertiaSharedDataAnalyzer in the container, update its overrides:
InertiaPageAnalyzer::buildPageData(),InertiaPageAnalyzer::buildTypeStringWithOverrides()andInertiaSharedDataAnalyzer::normalizeOverrideKeys()take new optional parameters. Add them to your override's signature, or PHP rejects the class.InertiaPageAnalyzer::parseTsCastsFromMethod()andInertiaSharedDataAnalyzer::parseTsCastsFromMiddleware()also return anoptionalOverridesmap of each entry's'optional'flag. An override that returns the old shape still works, but its entries' imports and'optional'flags are ignored.
Custom Resource Transformers
If you subclass ResourceTransformer and read the protected castKeysWithImport() method or the $importedCastKeys property, move to the new cast record. Both are gone.
Docblock Helpers
If your code calls LaravelTsPublish::extractReturnTypeFromDocblock() or LaravelTsPublish::parseArrayShapeToTsTypes(), check what they return. Both keep their signatures, but they read docblocks as Docblock Tags describes:
extractReturnTypeFromDocblock()returns the whole type a tag spells, such asstring | nullfor@return string | null, where it returnedstring.parseArrayShapeToTsTypes()also readsobject{...}shapes and quoted, numeric and hyphenated keys, which it left out, and returns a quoted key without its quotes.
Upgrading to 2.0 From 1.x
Version 2 aims to match everything Laravel Wayfinder provides, with a few things done differently.
New in Version 2
Version 2 adds these features:
- Route functions based on your routes and controllers, including return types for Inertia routes and Vue components, and pagination with the model or resource embedded automatically
- Form request interfaces
- Broadcast channels
- Broadcast event interfaces
- A Laravel Echo TypeScript augmentation
- Global Inertia route response parameters
- A Vite env augmentation file, built from the
.envsettings prefixed withVITE_ - A generation cache that makes reruns of the full
ts:publishcommand faster
Each feature's page in these docs shows the TypeScript it generates.
Recommended Upgrade Flow
Follow these steps in order:
- Update to the v2 package release in Composer.
- Republish the config and views with
--force. See Configuration Changes and Templates. - Install
@tolki/tsand remove@tolki/enum. See New npm Package. - Update your Vite plugin import to
@tolki/ts/vite. - Remove your old generated
datafolder. - Run a fresh publish with
php artisan ts:publish --fresh. - Fix the import paths in your app code to match the modular namespace output. See Modular Publishing Only.
Breaking Changes
Configuration Changes
The version 1 configuration was mostly flat. Version 2 has more features, so each main feature has its own config block.
Most version 1 settings move into their block, and the block name leaves the key: enum_template becomes enums.template, and publish_models becomes models.enabled.
If you published the config file, republish it with the --force flag:
php artisan vendor:publish --tag="ts-publish-config" --forceFull Configuration Update List
The tables below map every key from the flat version 1 config to its version 2 block. The recommended path is to republish the config file, then use your project's git diff to find the customizations you need to reapply.
Show the Full Key-by-Key Migration Table
1) Pipeline Class Overrides Moved Under Each Feature Group
| Old key | New key |
|---|---|
model_collector_class | models.collector_class |
model_generator_class | models.generator_class |
model_transformer_class | models.transformer_class |
model_writer_class | models.writer_class |
enum_collector_class | enums.collector_class |
enum_generator_class | enums.generator_class |
enum_transformer_class | enums.transformer_class |
enum_writer_class | enums.writer_class |
resource_collector_class | resources.collector_class |
resource_generator_class | resources.generator_class |
resource_transformer_class | resources.transformer_class |
resource_writer_class | resources.writer_class |
2) Shared Writer Overrides Renamed or Grouped
| Old key | New key |
|---|---|
barrel_writer_class | barrel_writer_class (same key, still supported as a shared override) |
globals_writer_class | globals.writer_class |
json_writer_class | json.writer_class |
watcher_json_writer_class | watcher.writer_class |
3) Template Key Migration
| Old key | New key |
|---|---|
model_template | models.template |
enum_template | enums.template |
resource_template | resources.template |
globals_template | globals.template |
Version 2 also adds template keys for the new features:
| New v2 template keys |
|---|
routes.template |
form_requests.template |
broadcast_channels.template |
broadcast_events.template |
broadcast_events.index_template |
broadcast_events.echo_augmentation.template |
4) Feature Enable Flags Moved From Flat Keys to Grouped Keys
| Old key | New key |
|---|---|
publish_enums | enums.enabled |
publish_models | models.enabled |
publish_resources | resources.enabled |
output_globals_file | globals.enabled |
output_json_file | json.enabled |
output_collected_files_json | watcher.enabled |
Version 2 adds these feature toggles:
| New v2 feature toggles |
|---|
routes.enabled |
form_requests.enabled |
broadcast_channels.enabled |
broadcast_events.enabled |
inertia.enabled |
vite_env.enabled |
cache.enabled |
5) Namespace and Casing Options Moved Under Feature Groups
| Old key | New key |
|---|---|
models_namespace | models.namespace |
enums_namespace | enums.namespace |
resources_namespace | resources.namespace |
relationship_case | models.relationship_case |
enum_method_case | enums.method_case |
nullable_relations | models.nullable_relations |
relation_nullability_map | models.relation_nullability_map |
The *.namespace keys have no effect in version 2. The globals file names each namespace after the class's PHP namespace, as described in Modular Publishing Only.
6) Include, Exclude, and Additional Directories Migrated Per Feature
| Old key | New key |
|---|---|
additional_model_directories | models.additional_directories |
included_models | models.included |
excluded_models | models.excluded |
additional_enum_directories | enums.additional_directories |
included_enums | enums.included |
excluded_enums | enums.excluded |
additional_resource_directories | resources.additional_directories |
included_resources | resources.included |
excluded_resources | resources.excluded |
These new version 2 blocks use the same include, exclude, and additional directories pattern:
| New v2 blocks using the same pattern |
|---|
form_requests.* |
broadcast_events.* |
7) Enum Metadata and Options Renamed and Regrouped
| Old key | New key |
|---|---|
enum_metadata_enabled | enums.metadata_enabled |
enums_use_tolki_package | enums.use_tolki_package |
auto_include_enum_methods | enums.auto_include_methods |
auto_include_enum_static_methods | enums.auto_include_static_methods |
8) Output File Naming and Output Directory Keys Grouped
| Old key | New key |
|---|---|
global_filename | globals.filename |
global_directory | globals.output_directory |
json_filename | json.filename |
json_output_directory | json.output_directory |
collected_files_json_filename | watcher.filename |
collected_files_json_output_directory | watcher.output_directory |
9) Modular Publishing Setting Removed
| Old key | Status in v2 |
|---|---|
modular_publishing | Removed. Modular output is always on. |
10) New Top-Level Config Groups in v2
These blocks did not exist in the version 1 config:
| New v2 top-level block |
|---|
cache.* |
routes.* |
form_requests.* |
broadcast_channels.* |
broadcast_events.* |
inertia.* |
vite_env.* |
Version 2 also adds this nested block:
| New v2 nested block |
|---|
broadcast_events.echo_augmentation.* |
11) Keys That Stayed the Same
These keys are still top-level and need no migration:
| Key | Status |
|---|---|
run_after_migrate | Unchanged (still top-level) |
output_to_files | Unchanged (still top-level) |
output_directory | Unchanged (still top-level) |
namespace_strip_prefix | Unchanged (still top-level) |
custom_ts_mappings | Unchanged (still top-level) |
timestamps_as_date | Unchanged (still top-level) |
ts_extends still exists, and version 2 adds sections beyond models and resources:
ts_extends key | v2 note |
|---|---|
ts_extends.form_requests | New section in v2 |
ts_extends.broadcast_events | New section in v2 |
New npm Package
To support functional routing as well as functional enums, install the new @tolki/ts package that goes with this Laravel package:
npm install @tolki/tsThen uninstall the previous @tolki/enum package. @tolki/ts supports both the version 1 functional enums and the new version 2 functional routing functions:
npm uninstall @tolki/enumIf you use the Vite plugin, update its import path in your Vite config file:
import { laravelTsPublish } from "@tolki/ts/vite";The build flag changed too. The Vite plugin from @tolki/enum calls ts:publish with the --only-enums option. The @tolki/ts Vite plugin calls it with --only-functional instead, which skips model and resource interfaces when building assets.
Templates
If you published and modified the Blade templates, publish them again and reapply your changes:
php artisan vendor:publish --tag="laravel-ts-publish-views" --forceTsResourceCasts Attribute Removed
The TsResourceCasts attribute (AbeTwoThree\LaravelTsPublish\Attributes\TsResourceCasts) has been removed.
Replace every use with TsCasts (AbeTwoThree\LaravelTsPublish\Attributes\TsCasts), which now handles resources, trait methods, models, and form requests the same way. The constructor signature and array format are identical. Only the class name changes:
// Before
use AbeTwoThree\LaravelTsPublish\Attributes\TsResourceCasts;
#[TsResourceCasts(['field' => 'string'])]
// After
use AbeTwoThree\LaravelTsPublish\Attributes\TsCasts;
#[TsCasts(['field' => 'string'])]Pipeline Customization
If you changed or extended a collector, generator, transformer, writer, or template in version 1, check that your changes still work with version 2. Then register your classes under the new *_class keys in each feature's block to override the package defaults. See Customizing the Pipeline.
Modular Publishing Only
In version 1, the default output was a flat directory, with a setting for modular publishing. Version 2 always publishes in the modular format, and there's no setting for a flat directory. With 7 large groups of features instead of 3, supporting both layouts was error-prone, so version 2 keeps only the modular one.
Update the import paths in your code to match the PHP namespace of each model, enum, and resource. Delete the data folder that holds your previous types, then run php artisan ts:publish --fresh, so the files you see match the version 2 output.
For example, take a model in this PHP namespace:
<?php
namespace App\Models\Users;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
//
}Its import path changes like this:
// Before
import type { User } from "@data/models";
// After
import type { User } from "@data/app/models/users";If you use the globals file, its namespaces follow your PHP namespaces too. A version 1 flat-mode type such as models.User becomes app.models.users.User for the model above. See Global Declaration File.
New Command Options and Behavior
Version 2 adds more selective ts:publish flags and a cache control:
# Every enabled feature except model and resource interfaces
php artisan ts:publish --only-functional
# One feature at a time
php artisan ts:publish --only-routes
php artisan ts:publish --only-form-requests
php artisan ts:publish --only-broadcast-channels
php artisan ts:publish --only-broadcast-events
# Rebuild the cache
php artisan ts:publish --freshThese flags follow three rules:
- You can pass only one
--only-*flag per command. --only-functionaltakes precedence and ignores other--only-*flags.--freshforces a full regeneration and cache rebuild.
See Limiting a Single Run With Flags for every flag.
New Config Groups in v2
Besides reorganizing the existing model, enum, and resource keys, version 2 adds these config blocks:
routes.*form_requests.*broadcast_channels.*broadcast_events.*inertia.*vite_env.*cache.*
If you published a version 1 config, republish it and reapply your customizations to the new block structure.
New Generated Files You Should Expect
Depending on which features are enabled, version 2 generates these files beyond enums, models, and resources:
- Route controller helper files
- Form request TypeScript interfaces
- Event parameter TypeScript interfaces
broadcast-channels.tsbroadcast-events.tsecho-broadcast-events.d.ts, when the Echo augmentation is enabledinertia-config.d.tsvite-env.d.ts, or your configured filename
Make sure your tsconfig.json include patterns cover these generated declaration files.
Generation Cache
Version 2 adds a generation cache that skips unchanged classes after the first run:
- Run
php artisan ts:publish --freshafter upgrading. - Use
--freshany time you need to guarantee a full rebuild.
See Cache Generation for how the cache works.