romegasoftware/laravel-schema-generator
Composer 安装命令:
composer require romegasoftware/laravel-schema-generator
包简介
Generate TypeScript Zod validation schemas from Laravel validation rules
README 文档
README
Generate TypeScript Schema validation schemas from your Laravel validation rules. This package supports Laravel FormRequest classes, Spatie Data classes, and custom validation classes through an extensible architecture.
It will generate Zod schema out of the box, but can be extended for different schema generators.
Features
- 🚀 Zero Dependencies - Works with vanilla Laravel
- 📦 Smart Package Detection - Automatically detects and uses installed packages
- 🎯 Multiple Validation Sources - FormRequests, Spatie Data classes, custom extractors
- 🔧 Flexible Configuration - Customize output paths, formats, and integration settings
- 🧩 Highly Extensible - Custom extractors and type handlers with priority system
Installation
composer require romegasoftware/laravel-schema-generator
Ensure Zod v4 is installed
npm install zod
Optional Packages
For additional features, install these optional packages:
# For Spatie Data class support composer require spatie/laravel-data # For TypeScript transformer integration composer require spatie/laravel-typescript-transformer
Configuration
To publish the configuration file, run:
php artisan vendor:publish --provider="RomegaSoftware\LaravelSchemaGenerator\LaravelSchemaGeneratorServiceProvider"
This will create a config/laravel-schema-generator.php file where you can customize output paths, formats, and integration settings.
Generating Separate Files
By default, all schemas are generated into a single TypeScript file. You can configure the package to generate separate files for each schema (e.g., UserSchema.ts, PostSchema.ts) by enabling separate_files in the configuration.
// config/laravel-schema-generator.php 'zod' => [ 'output' => [ 'path' => resource_path('js/types/schemas.ts'), // fallback/default path 'separate_files' => true, // Optional: specify a dedicated directory for separate files 'directory' => resource_path('js/types/schemas'), ], ],
When enabled, the generator will:
- Create individual
.tsfiles for each schema. - Automatically resolve and inject imports for dependent schemas (e.g., if
UserSchemareferencesAddressSchema).
Quick Start
- Add the attribute to your Laravel validation classes:
use RomegaSoftware\LaravelSchemaGenerator\Attributes\ValidationSchema; #[ValidationSchema] class CreateUserRequest extends FormRequest { public function rules(): array { return [ 'name' => 'required|string|max:255', 'email' => 'required|email', 'age' => 'nullable|integer|min:18', ]; } }
- Generate the schemas:
php artisan schema:generate
- Use in TypeScript:
import { CreateUserRequestSchema } from "@/types/schemas"; const result = CreateUserRequestSchema.safeParse(formData); if (result.success) { // Data is valid await api.createUser(result.data); }
Documentation
For complete documentation, configuration options, advanced features, and examples, visit:
📚 Official Documentation Coming Soon
Custom Schema Overrides
When you need to keep bespoke Laravel validation logic but still describe the TypeScript shape, provide a literal override using the fluent helper. Prefix the snippet with . when you want to append behaviour to the inferred Zod builder instead of replacing it entirely:
use RomegaSoftware\LaravelSchemaGenerator\Support\SchemaRule; 'items' => [ 'required', 'array', SchemaRule::make( static function ($attribute, $value, $fail, string $message): void { if (collect($value)->sum('qty') < 12) { $fail($message); } } ) ->append(static function (string $encodedMessage): string { return <<<ZOD .superRefine((items, ctx) => { const total = items.reduce((sum, item) => sum + item.qty, 0); if (total < 12) { ctx.addIssue({ code: 'custom', message: {$encodedMessage}, path: ['items'], }); } }) ZOD; }) ->failWith('You must order at least 12 total units.'), ],
Because the override begins with ., the generator keeps the inferred base (z.array(...)) and simply appends your refinement. The callable passed to append() receives the JSON-encoded message as its first argument (and the raw message as a second argument if you declare it). When you want to replace the builder outright, omit the leading dot and provide the complete Zod expression (for example z.array(z.object({ ... }))).
Prefer dedicated rule objects? Implement SchemaAnnotatedRule and reuse the same fluent API with the provided trait:
use Closure; use Illuminate\Contracts\Validation\ValidationRule; use RomegaSoftware\LaravelSchemaGenerator\Concerns\InteractsWithSchemaFragment; use RomegaSoftware\LaravelSchemaGenerator\Contracts\SchemaAnnotatedRule; final class TotalOrderItemsRule implements SchemaAnnotatedRule, ValidationRule { use InteractsWithSchemaFragment; public function __construct() { $this->withFailureMessage('You must order at least 12 total cases.') ->append(function (?string $encodedMessage) { return <<<ZOD .superRefine((items, ctx) => { const total = items.reduce((sum, item) => sum + item.quantity, 0); if (total < 12) { ctx.addIssue({ code: 'custom', message: {$encodedMessage}, path: ['items'] }); } }) ZOD; }); } /** * Run the validation rule. * * @param Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { if (collect($value)->sum('quantity') < 12) { $fail($this->failureMessage() ?? 'You must order at least 12 total units.'); } } }
Both approaches surface the schema fragment directly alongside the validation logic and are picked up automatically by the generator for FormRequests and Spatie Data classes.
Contributing
Please see CONTRIBUTING for development setup and contribution guidelines.
License
The MIT License (MIT). Please see License File for more information.
Credits
romegasoftware/laravel-schema-generator 适用场景与选型建议
romegasoftware/laravel-schema-generator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 20.78k 次下载、GitHub Stars 达 32, 最近一次更新时间为 2025 年 09 月 16 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「generator」 「schema」 「validation」 「laravel」 「typescript」 「zod」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 romegasoftware/laravel-schema-generator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 romegasoftware/laravel-schema-generator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 romegasoftware/laravel-schema-generator 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Memio's PrettyPrinter, used to generate PHP code from given Model
Extension for Opis JSON Schema
EAV modeling package for Eloquent and Laravel.
serialize Symfony Forms into JSON schema
Build forms from schema
Specifications like JSON schemas and other things for mosparo
统计信息
- 总下载量: 20.78k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 32
- 点击次数: 32
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-09-16