- Notifications
You must be signed in to change notification settings - Fork1
Generate typescript schemas for zod and others from your Laravel Requests and Spatie Data files.
License
romegasoftware/laravel-schema-generator
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
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.
- 🚀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
composer require romegasoftware/laravel-schema-generator
Ensure Zod v4 is installed
npm install zod
For additional features, install these optional packages:
# For Spatie Data class supportcomposer require spatie/laravel-data# For TypeScript transformer integrationcomposer require spatie/laravel-typescript-transformer
To publish the configuration file, run:
php artisan vendor:publish --provider="RomegaSoftware\LaravelSchemaGenerator\LaravelSchemaGeneratorServiceProvider"This will create aconfig/laravel-schema-generator.php file where you can customize output paths, formats, and integration settings.
- Add the attribute to your Laravel validation classes:
useRomegaSoftware\LaravelSchemaGenerator\Attributes\ValidationSchema;#[ValidationSchema]class CreateUserRequestextends FormRequest{publicfunctionrules():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";constresult=CreateUserRequestSchema.safeParse(formData);if(result.success){// Data is validawaitapi.createUser(result.data);}
For complete documentation, configuration options, advanced features, and examples, visit:
📚Official Documentation Coming Soon
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:
useRomegaSoftware\LaravelSchemaGenerator\Support\SchemaRule;'items' => ['required','array', SchemaRule::make(staticfunction ($attribute,$value,$fail,string$message):void {if (collect($value)->sum('qty') <12) {$fail($message); } } ) ->append(staticfunction (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 toappend() 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 examplez.array(z.object({ ... }))).
Prefer dedicated rule objects? ImplementSchemaAnnotatedRule and reuse the same fluent API with the provided trait:
useClosure;useIlluminate\Contracts\Validation\ValidationRule;useRomegaSoftware\LaravelSchemaGenerator\Concerns\InteractsWithSchemaFragment;useRomegaSoftware\LaravelSchemaGenerator\Contracts\SchemaAnnotatedRule;finalclass TotalOrderItemsRuleimplements SchemaAnnotatedRule, ValidationRule{use InteractsWithSchemaFragment;publicfunction__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 */publicfunctionvalidate(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.
Please seeCONTRIBUTING for development setup and contribution guidelines.
The MIT License (MIT). Please seeLicense File for more information.
About
Generate typescript schemas for zod and others from your Laravel Requests and Spatie Data files.
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.