PHPackages                             codemystify/laravel-types-generator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. codemystify/laravel-types-generator

ActiveLibrary[API Development](/categories/api)

codemystify/laravel-types-generator
===================================

Simplified TypeScript types generator for Laravel applications with developer-defined structure system

0.6(1y ago)3244MITPHPPHP ^8.2|^8.3CI failing

Since May 26Pushed 1y agoCompare

[ Source](https://github.com/codestify/laravel-types-generator)[ Packagist](https://packagist.org/packages/codemystify/laravel-types-generator)[ Docs](https://github.com/codemystify/laravel-types-generator)[ RSS](/packages/codemystify-laravel-types-generator/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (6)Dependencies (9)Versions (7)Used By (0)

Laravel Types Generator
=======================

[](#laravel-types-generator)

I got tired of manually writing TypeScript types for my Laravel APIs, so I built this. It's simple: you tell it exactly what your data looks like, and it generates clean TypeScript interfaces. No magic, no guessing, just straight-forward type generation.

What This Actually Does
-----------------------

[](#what-this-actually-does)

You add an attribute to your Laravel classes (like API resources), define the structure, run a command, and get TypeScript files. That's it.

Installation
------------

[](#installation)

```
composer require codemystify/laravel-types-generator
```

If you want to customize the config:

```
php artisan vendor:publish --tag=types-generator-config
```

Quick Example
-------------

[](#quick-example)

Here's how I use it in my Laravel API resources:

```
use Codemystify\TypesGenerator\Attributes\GenerateTypes;

class UserResource extends JsonResource
{
    #[GenerateTypes(
        name: 'User',
        structure: [
            'id' => 'number',
            'name' => 'string',
            'email' => 'string',
            'avatar' => ['type' => 'string', 'optional' => true],
            'created_at' => 'string',
        ]
    )]
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'avatar' => $this->avatar,
            'created_at' => $this->created_at->toISOString(),
        ];
    }
}
```

Run the command:

```
php artisan types:generate
```

Get this TypeScript file:

```
// user.ts
export interface User {
  id: number;
  name: string;
  email: string;
  avatar?: string;
  created_at: string;
}
```

How to Define Types
-------------------

[](#how-to-define-types)

### Basic Types

[](#basic-types)

```
[
    'title' => 'string',
    'count' => 'number',
    'active' => 'boolean',
    'data' => 'any',        // Use sparingly
]
```

### Optional Fields

[](#optional-fields)

For fields that might not be present:

```
[
    'bio' => ['type' => 'string', 'optional' => true],  // bio?: string
]
```

### Nullable Fields

[](#nullable-fields)

For fields that can be null:

```
[
    'deleted_at' => ['type' => 'string', 'nullable' => true],  // deleted_at: string | null
]
```

### Arrays

[](#arrays)

```
[
    'tags' => 'string[]',     // Array of strings
    'users' => 'User[]',      // Array of User interfaces
]
```

### Union Types

[](#union-types)

```
[
    'status' => 'string|null',  // status: string | null
]
```

Real Example: Blog Post API
---------------------------

[](#real-example-blog-post-api)

Here's how I handle a typical blog post resource:

```
class PostResource extends JsonResource
{
    #[GenerateTypes(
        name: 'Post',
        structure: [
            'id' => 'number',
            'title' => 'string',
            'slug' => 'string',
            'content' => 'string',
            'excerpt' => ['type' => 'string', 'nullable' => true],
            'published' => 'boolean',
            'author' => 'Author',
            'tags' => 'string[]',
            'created_at' => 'string',
            'updated_at' => 'string',
        ],
        types: [
            'Author' => [
                'id' => 'number',
                'name' => 'string',
                'email' => 'string',
                'avatar' => ['type' => 'string', 'optional' => true],
            ]
        ]
    )]
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'content' => $this->content,
            'excerpt' => $this->excerpt,
            'published' => $this->published,
            'author' => [
                'id' => $this->user->id,
                'name' => $this->user->name,
                'email' => $this->user->email,
                'avatar' => $this->user->avatar,
            ],
            'tags' => $this->tags->pluck('name')->toArray(),
            'created_at' => $this->created_at->toISOString(),
            'updated_at' => $this->updated_at->toISOString(),
        ];
    }
}
```

This generates two clean interfaces:

```
// post.ts
import type { Author } from './author';

export interface Post {
  id: number;
  title: string;
  slug: string;
  content: string;
  excerpt: string | null;
  published: boolean;
  author: Author;
  tags: string[];
  created_at: string;
  updated_at: string;
}

export interface Author {
  id: number;
  name: string;
  email: string;
  avatar?: string;
}
```

Commands
--------

[](#commands)

### Generate Types

[](#generate-types)

```
php artisan types:generate
```

### Preview Without Writing Files

[](#preview-without-writing-files)

```
php artisan types:generate --dry-run
```

### Generate Specific Group

[](#generate-specific-group)

```
php artisan types:generate --group=api
```

Using Groups
------------

[](#using-groups)

I organize my types with groups:

```
#[GenerateTypes(
    name: 'AdminUser',
    structure: [...],
    group: 'admin'
)]

#[GenerateTypes(
    name: 'PublicPost',
    structure: [...],
    group: 'public'
)]
```

Then generate specific groups:

```
php artisan types:generate --group=admin
```

File Organization
-----------------

[](#file-organization)

All generated files go to `resources/js/types/generated/` by default:

```
resources/js/types/generated/
├── index.ts          # Exports everything
├── user.ts
├── post.ts
├── admin-user.ts
└── ...

```

The `index.ts` file automatically exports everything:

```
export * from './user';
export * from './post';
export * from './admin-user';
```

So in your React/Vue components:

```
import { User, Post } from '@/types/generated';
```

Configuration
-------------

[](#configuration)

The defaults work fine, but you can customize:

```
// config/types-generator.php
return [
    'sources' => [
        'app/Http/Resources',
        'app/Http/Controllers',
        'app/Models',
    ],

    'output' => [
        'base_path' => 'resources/js/types/generated',
    ],

    'files' => [
        'extension' => 'ts',
        'naming_pattern' => 'kebab-case',
        'add_header_comment' => true,
    ],
];
```

Practical Tips
--------------

[](#practical-tips)

### 1. Start Simple

[](#1-start-simple)

Don't try to define everything at once. Start with basic types and add complexity as needed.

### 2. Mirror Your API Exactly

[](#2-mirror-your-api-exactly)

The structure should match exactly what your API returns. Don't overthink it.

### 3. Use Optional vs Nullable Correctly

[](#3-use-optional-vs-nullable-correctly)

- `optional: true` - field might not exist in the response
- `nullable: true` - field exists but can be null

### 4. Handle Pagination

[](#4-handle-pagination)

```
#[GenerateTypes(
    name: 'PaginatedPosts',
    structure: [
        'data' => 'Post[]',
        'meta' => 'PaginationMeta',
    ],
    types: [
        'PaginationMeta' => [
            'current_page' => 'number',
            'last_page' => 'number',
            'per_page' => 'number',
            'total' => 'number',
        ]
    ]
)]
```

### 5. Keep It DRY with Shared Types

[](#5-keep-it-dry-with-shared-types)

Define common types once and reuse them:

```
// In a base resource or dedicated class
'address' => 'Address',

types: [
    'Address' => [
        'street' => 'string',
        'city' => 'string',
        'country' => 'string',
        'postal_code' => 'string',
    ]
]
```

Why I Built This
----------------

[](#why-i-built-this)

I tried other solutions but they were either:

- Too magic (trying to guess types from code)
- Too complicated (requiring tons of configuration)
- Too unreliable (breaking when Laravel code changed)

This approach is explicit and predictable. You define exactly what you want, and you get exactly that. No surprises.

Troubleshooting
---------------

[](#troubleshooting)

### Types not generating?

[](#types-not-generating)

- Make sure you're using the attribute in classes that the scanner can find
- Check that your `sources` config includes the right directories
- Run with `--dry-run` to see what would be generated

### Import errors in TypeScript?

[](#import-errors-in-typescript)

- The generator creates proper import statements automatically
- Make sure you're importing from the right path
- Check that the `index.ts` file was generated

### Want to disable the package in production?

[](#want-to-disable-the-package-in-production)

The attributes have no runtime impact, but if you want to remove them:

```
php artisan types:cleanup --remove-attributes
```

That's it! Simple, predictable TypeScript type generation for Laravel. No magic, just the types you define.

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance47

Moderate activity, may be stable

Popularity15

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

6

Last Release

391d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3cc32620a69f8281cf0555a5b707401bed165b6458f1e7e4cbd39bb4c08f28c4?d=identicon)[codestify](/maintainers/codestify)

---

Top Contributors

[![codestify](https://avatars.githubusercontent.com/u/60575042?v=4)](https://github.com/codestify "codestify (13 commits)")

---

Tags

phpapilaravelautomationjavascriptgeneratordevelopmenttypescriptinertiafrontendresourcestypes

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/codemystify-laravel-types-generator/health.svg)

```
[![Health](https://phpackages.com/badges/codemystify-laravel-types-generator/health.svg)](https://phpackages.com/packages/codemystify-laravel-types-generator)
```

###  Alternatives

[laravel/ai

The official AI SDK for Laravel.

9782.1M161](/packages/laravel-ai)[laravel/wayfinder

Generate TypeScript representations of your Laravel actions and routes.

1.7k7.0M116](/packages/laravel-wayfinder)[tightenco/jigsaw

Simple static sites with Laravel's Blade.

2.3k449.3k30](/packages/tightenco-jigsaw)[erag/laravel-lang-sync-inertia

A powerful Laravel package for syncing and managing language translations across backend and Inertia.js (Vue/React) frontends, offering effortless localization, auto-sync features, and smooth multi-language support for modern Laravel applications.

4821.5k](/packages/erag-laravel-lang-sync-inertia)[calebdw/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

15104.9k4](/packages/calebdw-larastan)[alibori/laravel-api-resource-generator

Package to generate API resources from models.

222.6k](/packages/alibori-laravel-api-resource-generator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
