Eloquent Models β
Laravel TypeGen inspects your Eloquent models to generate precise TypeScript interfaces. It automatically maps database column types, model casts, timestamps, hidden attributes, and relationships.
Column Mapping & Casts β
The generator maps Eloquent attributes using the following precedence rules:
- Primary Key: Identified by
getKeyName(). IfgetKeyType()isint, it maps tonumber, otherwisestring. - Casts: Attributes listed in
$casts(orcasts()) are mapped based on their cast type (e.g.booleantoboolean,integertonumber). - Fillable attributes: Columns listed in
$fillablethat are not cast are assumed to be of typestring. - Timestamps: If
$timestampsis enabled,created_atandupdated_at(or custom columns) are automatically generated asstring.
Live Schema Inspection & Offline Fallback β
TypeGen queries your live database tables using Schema::getColumns() to extract exact column types, nullability, and database defaults.
If your database tables are not yet migrated (or when running in offline CI environments):
- Pass the
--skip-db-checkCLI option, or - Set
'strict_schema' => falseinconfig/typegen.php
When strict schema checking is bypassed, TypeGen gracefully falls back to inspecting $fillable, $casts, and PHPDoc @property annotations without failing.
Customizing Names β
By default, the interface name matches the PHP class name. You can customize the name of the exported interface by passing a parameter to the attribute:
#[TypeScript(name: 'AdminUser')]
class User extends Model {}This will output:
export interface AdminUser { ... }Hidden Attributes β
Attributes listed in $hidden are omitted from the generated TS interface by default. You can change this behavior in config/typegen.php by setting 'include_hidden' => true.
Appended Attributes & Accessors β
If you append attributes using $appends, TypeGen will automatically include them. It performs deep reflection to infer the exact return type:
- Legacy Accessors: Methods like
public function getIsAdminAttribute(): boolcorrectly yieldisAdmin: boolean. - Modern Accessors: Laravel 9+
Attribute::make()getters are also fully supported. TypeGen evaluates the underlying closure signature to extract the precise return type instead of defaulting toany.
Relationships β
TypeGen supports auto-generation of Eloquent relationships. You must explicitly opt-in to relations on each model using the includeRelations parameter:
#[TypeScript(includeRelations: ['posts', 'profile'])]
class User extends Model
{
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
public function profile(): HasOne
{
return $this->hasOne(Profile::class);
}
}Auto-Discovery β
When you include relationships, TypeGen uses a Breadth-First Search (BFS) graph walk to auto-discover and generate the related models (Post and Profile), even if they aren't marked with the #[TypeScript] attribute.
Generated types are automatically marked optional (?) with | null matching the runtime database nullable state:
export interface User {
id: number;
posts?: Post[];
profile?: Profile | null;
}Polymorphic Relations β
Polymorphic MorphTo relationships are supported out of the box when a morph map is registered:
// AppServiceProvider.php
Relation::enforceMorphMap([
'post' => Post::class,
'video' => Video::class,
]);Which yields:
export interface Comment {
commentable?: (Post | Video) | null;
}If no morph map is registered, the relation defaults to unknown | null.
BelongsTo Nullability β
When inspecting a live database schema, BelongsTo relations check whether the underlying foreign key column is nullable:
- Nullable foreign key (or DB-less fallback) β
Relation<User | null> - Non-nullable foreign key β
Relation<User>
Pivot Table Typing (BelongsToMany / MorphToMany) β
Relations using ->withPivot(...), ->withTimestamps(), or custom pivot accessors (->as('membership')) automatically emit pivot intersection types resolved from custom Pivot model casts or the pivot table schema:
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class)
->withPivot('assigned_by', 'is_primary')
->withTimestamps();
}Generates:
roles?: Relation<(Role & { pivot: { assigned_by: string | null; is_primary: boolean; created_at: string | null; updated_at: string | null } })[]>;Virtual Aggregate Attributes (withCount, withExists, withSum) β
Declare virtual aggregate attributes on #[TypeScript] (supports Laravel 'relation as alias' and 'relation:column' syntax) or via Model::$withCount:
#[TypeScript(
includeRelations: ['roles'],
withCount: ['roles', 'roles as active_roles_count'],
withExists: ['roles'],
withSum: ['roles:priority'],
)]
class User extends Model {}Generates optional fields:
roles_count?: number;
active_roles_count?: number;
roles_exists?: boolean;
roles_sum_priority?: number | null;