Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Typescriptable Laravel Laravel Package

kiwilan/typescriptable-laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the PHP package:

    composer require kiwilan/typescriptable-laravel
    
  2. Publish the config (optional but recommended for customization):

    php artisan vendor:publish --provider="Kiwilan\Typescriptable\TypescriptableServiceProvider"
    
  3. Run the generator for Eloquent models:

    php artisan typescriptable:generate
    
    • Outputs TypeScript types to resources/js/types/eloquent/.
  4. First use case: Use the generated types in your Inertia/Vue/React components:

    import type { User } from '@/types/eloquent/User';
    
    const user: User = await getUser(); // Type-safe access to model attributes
    

Key Files to Review

  • config/typescriptable.php – Customize output paths, naming conventions, and included models.
  • resources/js/types/ – Default output directory for generated TypeScript files.
  • app/Models/ – Ensure your Eloquent models are properly defined (e.g., casts, relations).

Implementation Patterns

1. Model Typing Workflow

  • Automatic Generation: Run php artisan typescriptable:generate to generate types for all Eloquent models in app/Models/.

    php artisan typescriptable:generate --models=User,Post --output=custom/path
    
    • Supports --models to generate types for specific models only.
    • Supports --output to override the default output directory.
  • Including/Excluding Models: Configure config/typescriptable.php to specify which models to include/exclude:

    'models' => [
        'include' => ['App\Models\User', 'App\Models\Post'],
        'exclude' => ['App\Models\TempModel'],
    ],
    
  • Handling Relations: The package automatically infers relation types (e.g., belongsTo, hasMany). Example:

    // Generated for a User model with a 'posts' relation
    interface User {
        posts: Post[];
    }
    

2. Route Typing

  • Generate Route Types:

    php artisan typescriptable:routes
    

    Outputs types for Laravel routes to resources/js/types/routes.ts. Example:

    interface Routes {
        'users.index': '/users';
        'users.show': (id: number) => `/users/${id}`;
    }
    
  • Integration with Inertia: Use the generated route types in Inertia links:

    import { routes } from '@/types/routes';
    
    <Link href={routes['users.show'](user.id)}>View User</Link>
    

3. Spatie Settings Typing

  • Generate Settings Types:
    php artisan typescriptable:settings
    
    Outputs types for Spatie Laravel Settings to resources/js/types/settings.ts. Example:
    interface AppSettings {
        site_name: string;
        maintenance_mode: boolean;
    }
    

4. Customizing Type Generation

  • Override Default Naming: Use the type_map config to customize how models are named in TypeScript:

    'type_map' => [
        'App\Models\User' => 'AppUser', // Custom type name
    ],
    
  • Excluding Attributes: Use the ignored_attributes config to exclude sensitive fields:

    'ignored_attributes' => ['password', 'api_token'],
    

5. Integration with Inertia

  • Install the NPM package for helpers:
    npm install @kiwilan/typescriptable-laravel
    
  • Use the useTypescriptable composable in Vue/Inertia:
    <script setup>
    import { useTypescriptable } from '@kiwilan/typescriptable-laravel';
    
    const { getModelType } = useTypescriptable();
    const userType = getModelType('App\Models\User'); // Returns 'User'
    </script>
    

Gotchas and Tips

Pitfalls

  1. Circular Dependencies in Relations:

    • If models have circular relations (e.g., User has Post, Post has User), the generator may fail or produce incomplete types.
    • Fix: Use --force flag or manually adjust the generated types:
      php artisan typescriptable:generate --force
      
  2. Dynamic Attributes or JSON Columns:

    • The package may not fully infer types for dynamic attributes or JSON columns (e.g., json: array).
    • Fix: Manually extend the generated types or use custom casts with explicit types:
      protected $casts = [
          'metadata' => 'array<string, mixed>',
      ];
      
  3. Namespace Conflicts:

    • If your model namespaces conflict with TypeScript keywords (e.g., class, interface), the generator may fail.
    • Fix: Use the type_map config to rename the types:
      'type_map' => [
          'App\Models\ClassName' => 'ClassNameModel',
      ],
      
  4. Inertia Page Typing:

    • The package does not automatically type Inertia page props. You must manually extend the generated types:
      import { PageProps } from '@inertiajs/core';
      import type { User } from '@/types/eloquent/User';
      
      interface UserShowPageProps extends PageProps {
          user: User;
      }
      

Debugging

  1. Check Generator Logs: Run the generator with --verbose to debug issues:

    php artisan typescriptable:generate --verbose
    
  2. Validate Model Definitions: Ensure all Eloquent models:

    • Use proper namespace (App\Models\).
    • Define casts and relations explicitly (e.g., belongsTo, hasMany).
    • Avoid dynamic properties (e.g., $append, $hidden) that break type inference.
  3. Clear Cache: If types aren’t updating, clear Laravel and TypeScript caches:

    php artisan cache:clear
    npm run dev
    

Tips

  1. Partial Generation: Regenerate only specific models for faster iterations:

    php artisan typescriptable:generate --models=User
    
  2. Watch Mode (NPM): Use the NPM package to watch for model changes and auto-regenerate types:

    npm run typescriptable:watch
    
  3. Custom TypeScript Config: Extend the generated types in a separate file (e.g., resources/js/types/extensions.ts):

    declare module '@/types/eloquent/User' {
        interface User {
            fullName: string; // Computed property
        }
    }
    
  4. MongoDB Support: For MongoDB models, ensure the jenssegers/laravel-mongodb package is installed and models extend \Jenssegers\Mongodb\Eloquent\Model.

  5. CI/CD Integration: Add the generator to your CI pipeline to ensure types are always up-to-date:

    # Example GitHub Actions step
    - run: php artisan typescriptable:generate
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle