arnaldo-tomo/laravel-autoscema
Composer 安装命令:
composer require arnaldo-tomo/laravel-autoscema
包简介
Automatically generate TypeScript types and validation schemas from Laravel Models with zero configuration
README 文档
README
🚀 Automatically generate TypeScript types and validation schemas from Laravel Models with zero configuration.
✨ Features
- 🔄 Zero Configuration - Works out of the box with intelligent defaults
- 📝 TypeScript Types - Generate perfect TypeScript interfaces from Eloquent models
- 🔗 Relationships - Automatically handle Eloquent relationships
- ✅ Validation Schemas - Generate Zod/Yup schemas from Form Requests
- 🌐 API Client - Generate typed API clients for your endpoints
- 👁️ File Watcher - Real-time regeneration when models change
- 🎯 Framework Integration - Perfect for Inertia.js, React, Vue, and more
🚀 Quick Start
Installation
composer require arnaldo-tomo/laravel-autoscema
Initialize
php artisan schema:init
Generate Types
# Generate for specific models
php artisan schema:generate --model=User --model=Post
That's it! Your TypeScript types are ready in resources/js/types/.
📋 Example
Laravel Model
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $fillable = ['name', 'email', 'age']; protected $casts = [ 'email_verified_at' => 'datetime', 'preferences' => 'json', ]; public function posts() { return $this->hasMany(Post::class); } }
Generated TypeScript
// Generated at 2025-01-20 10:30:00 by Laravel AutoSchema export interface User { id: number; name: string; email: string; age: number; preferences: Record<string, any> | null; email_verified_at: Date | null; created_at: Date; updated_at: Date; // Relationships posts?: Post[]; } export type UserType = User;
Form Request Integration
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class CreateUserRequest extends FormRequest { public function rules() { return [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users', 'age' => 'nullable|integer|min:18', ]; } }
Generated Validation Schema
// Generated Zod schema export const createUserSchema = z.object({ name: z.string().max(255), email: z.string().email(), age: z.number().min(18).nullable(), }); export type CreateUserInput = z.infer<typeof createUserSchema>;
🛠️ Commands
Generate Types
# Generate all types # Generate for specific models php artisan schema:generate --model=User --model=Post # Preview without writing files php artisan schema:generate --dry-run # Force overwrite existing files php artisan schema:generate --force
File Watcher
# Watch for changes and regenerate automatically php artisan schema:watch # Watch with custom interval php artisan schema:watch --interval=5 # Watch in quiet mode php artisan schema:watch --quiet
⚙️ Configuration
Publish the configuration file:
php artisan vendor:publish --provider="ArnaldoTomo\LaravelAutoSchema\AutoSchemaServiceProvider" --tag="autoscema-config"
Configuration Options
<?php return [ 'output' => [ 'path' => resource_path('js/types'), 'filename_case' => 'pascal', // pascal, camel, snake, kebab 'export_format' => 'named', // named, default, namespace ], 'models' => [ 'directories' => [ app_path('Models'), ], 'include_relationships' => true, 'include_accessors' => true, ], 'validation' => [ 'enabled' => true, 'schema_format' => 'zod', // zod, yup, joi 'include_form_requests' => true, ], 'api' => [ 'generate_client' => true, 'authentication' => 'sanctum', // sanctum, passport, none ], ];
🔧 Advanced Usage
API Client Generation
When enabled, AutoSchema generates a complete API client:
// Generated API client import { userApi } from './types/api-client'; // Usage const users = await userApi.getAll(); const user = await userApi.getById(1); const newUser = await userApi.create({ name: 'John', email: 'john@example.com' });
Custom Types
Handle complex relationships and custom types:
class Product extends Model { protected $casts = [ 'metadata' => 'json', 'status' => ProductStatus::class, // Enum ]; public function variants() { return $this->hasMany(ProductVariant::class); } }
Generated TypeScript:
export interface Product { id: number; name: string; metadata: Record<string, any> | null; status: ProductStatus; // Relationships variants?: ProductVariant[]; } export enum ProductStatus { ACTIVE = 'active', INACTIVE = 'inactive', DRAFT = 'draft', }
Integration with Frontend Frameworks
React + TypeScript
import { User } from './types'; interface UserCardProps { user: User; // Fully typed! } const UserCard: React.FC<UserCardProps> = ({ user }) => { return ( <div> <h3>{user.name}</h3> <p>{user.email}</p> {user.posts && ( <span>{user.posts.length} posts</span> )} </div> ); };
Vue + TypeScript
<template> <div> <h3>{{ user.name }}</h3> <p>{{ user.email }}</p> </div> </template> <script setup lang="ts"> import type { User } from './types'; defineProps<{ user: User; }>(); </script>
Inertia.js
import { User } from './types'; interface Props { users: User[]; } const UsersIndex: React.FC<Props> = ({ users }) => { // users is fully typed! };
🔄 Workflow Integration
GitHub Actions
name: Generate Types on: push: paths: - 'app/Models/**' - 'database/migrations/**' - 'app/Http/Requests/**' jobs: generate-types: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: '8.2' - name: Install dependencies run: composer install - name: Generate TypeScript types run: php artisan schema:generate - name: Commit generated types run: | git config --local user.email "action@github.com" git config --local user.name "GitHub Action" git add resources/js/types/ git commit -m "Update TypeScript types" || exit 0 git push
Pre-commit Hook
#!/bin/sh # .git/hooks/pre-commit # Check if any model files changed if git diff --cached --name-only | grep -q "app/Models\|database/migrations\|app/Http/Requests"; then echo "🔄 Regenerating TypeScript types..." php artisan schema:generate --force # Add generated files to commit git add resources/js/types/ echo "✅ TypeScript types updated" fi
🎯 Use Cases
E-commerce Platform
class Product extends Model { protected $fillable = ['name', 'price', 'description']; protected $casts = [ 'price' => 'decimal:2', 'metadata' => 'json', 'status' => ProductStatus::class, ]; public function category() { return $this->belongsTo(Category::class); } public function variants() { return $this->hasMany(ProductVariant::class); } }
Generated types enable perfect frontend integration:
// Product listing with full type safety const ProductCard: React.FC<{ product: Product }> = ({ product }) => { return ( <div className="product-card"> <h3>{product.name}</h3> <p className="price">${product.price}</p> <p className="category">{product.category?.name}</p> <div className="variants"> {product.variants?.map(variant => ( <span key={variant.id}>{variant.name}</span> ))} </div> </div> ); };
API Integration
// Fully typed API calls const products = await productApi.getAll({ category: 'electronics', status: ProductStatus.ACTIVE }); const product = await productApi.getById(1); const newProduct = await productApi.create({ name: 'New Product', price: 99.99, description: 'Amazing product' });
Form Validation
// Form with automatic validation const ProductForm: React.FC = () => { const { register, handleSubmit, formState: { errors } } = useForm<CreateProductInput>({ resolver: zodResolver(createProductSchema) }); const onSubmit = async (data: CreateProductInput) => { // data is fully typed and validated await productApi.create(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register('name')} placeholder="Product name" /> {errors.name && <span>{errors.name.message}</span>} <input {...register('price', { valueAsNumber: true })} /> {errors.price && <span>{errors.price.message}</span>} </form> ); };
🔧 Troubleshooting
Common Issues
Types not generating?
- Check if models extend
Illuminate\Database\Eloquent\Model - Ensure output directory is writable
- Run with
--dry-runto see what would be generated
php artisan schema:generate --dry-run
Relationships not showing?
- Ensure relationships return
Illuminate\Database\Eloquent\Relations\Relation - Check if
include_relationshipsis enabled in config - Verify relationship methods are public
Custom types not working?
- Add custom type mappings in configuration
- Use
--forceto overwrite existing files - Check Laravel logs for errors
Debug Mode
# Enable verbose output php artisan schema:generate -v # Show detailed analysis php artisan schema:generate --dry-run -v
🧪 Testing
# Run package tests composer test # Run with coverage composer test-coverage # Run code formatting composer format
🤝 Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
Development Setup
# Clone repository git clone https://github.com/arnaldo-tomo/laravel-autoscema.git cd laravel-autoscema # Install dependencies composer install # Run tests composer test # Format code composer format
📜 Changelog
Please see CHANGELOG.md for recent changes.
🛡️ Security
If you discover any security-related issues, please email me@arnaldotomo.dev instead of using the issue tracker.
📄 License
Laravel AutoSchema is open-sourced software licensed under the MIT license.
🙏 Credits
- Arnaldo Tomo - Creator and maintainer
- All Contributors
🎉 Support
- ⭐ Star the project on GitHub
- 🐛 Report issues on GitHub Issues
- 💡 Request features on GitHub Discussions
- 📖 Read the documentation
Made with ❤️ by Arnaldo Tomo in Mozambique 🇲🇿
arnaldo-tomo/laravel-autoscema 适用场景与选型建议
arnaldo-tomo/laravel-autoscema 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.04k 次下载、GitHub Stars 达 21, 最近一次更新时间为 2025 年 07 月 18 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「validation」 「laravel」 「eloquent」 「types」 「typescript」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 arnaldo-tomo/laravel-autoscema 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 arnaldo-tomo/laravel-autoscema 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 arnaldo-tomo/laravel-autoscema 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A PSR-7 compatible library for making CRUD API endpoints
Adds request-parameter validation to the SLIM 3.x PHP framework
A jQuery augmented PHP library for creating and validating HTML forms
A Laravel validator for delimiter-separated list of emails.
A CakePHP behavior to validate foreign keys
PHP Validator for stuff.
统计信息
- 总下载量: 1.04k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 21
- 点击次数: 33
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-18