PHPackages                             maan511/openapi-to-laravel - 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. maan511/openapi-to-laravel

ActiveLibrary[API Development](/categories/api)

maan511/openapi-to-laravel
==========================

Bringing API-first development to Laravel

v0.2.0(7mo ago)015[1 PRs](https://github.com/Maan511/openapi-to-laravel/pulls)MITPHPPHP ^8.3CI passing

Since Sep 25Pushed 7mo agoCompare

[ Source](https://github.com/Maan511/openapi-to-laravel)[ Packagist](https://packagist.org/packages/maan511/openapi-to-laravel)[ GitHub Sponsors](https://github.com/Maan511)[ RSS](/packages/maan511-openapi-to-laravel/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (9)Versions (4)Used By (0)

OpenAPI to Laravel
==================

[](#openapi-to-laravel)

[![PHP Version](https://camo.githubusercontent.com/ef0054230522e542bc1f908ac005c6c75888dea255bac910f9015e12095e31d7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e332d626c7565)](https://www.php.net/releases/8.3/en.php)[![Laravel](https://camo.githubusercontent.com/c5fe755dfd47b9b4bc43057da623c24960423ff2ad0739f5d874736d34b94e7a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d25354531312e302d726564)](https://laravel.com)[![Tests](https://camo.githubusercontent.com/f3d59aabff905e2e09d3e1b80623b50094f8ab04aa7f9ed4e8e3b9b802d360df/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d70617373696e672d677265656e)](https://github.com/maan511/openapi-to-laravel)

Build Laravel APIs that stay perfectly synchronized with your OpenAPI specification. Automatically generate FormRequest validation and verify route compliance, ensuring your implementation always matches your API contract.

The Problem
-----------

[](#the-problem)

- **Time-consuming manual work**: Writing FormRequest classes for each endpoint takes 5-15 minutes per class
- **Documentation drift**: API documentation gets out of sync with validation rules and actual routes over time
- **Error-prone process**: Manual validation rule creation leads to inconsistencies and bugs
- **Route mismatches**: Laravel routes don't match OpenAPI specification, breaking API contracts
- **Maintenance overhead**: Changing OpenAPI specs requires tedious updates across multiple FormRequest files and route validation

The Solution
------------

[](#the-solution)

Two powerful commands that keep your Laravel application and OpenAPI specification perfectly synchronized:

**1. Generate FormRequest classes:**

```
php artisan openapi-to-laravel:make-requests api-spec.yaml
```

Automatically generates complete Laravel FormRequest classes with comprehensive validation rules from your OpenAPI specification. Supports all OpenAPI 3.x schema types, formats, constraints, nested objects, arrays, and reference resolution.

**2. Validate route consistency:**

```
php artisan openapi-to-laravel:validate-routes api-spec.yaml
```

Validates that your Laravel routes match your OpenAPI specification endpoints. Detects missing documentation, missing implementations, method mismatches, parameter differences, and provides detailed coverage statistics.

**Result:** Transform 100+ endpoints into perfectly validated FormRequest classes AND ensure your routes match your documentation - all in seconds, not hours.

Key Benefits
------------

[](#key-benefits)

- **Save hours of development time**: Generate comprehensive FormRequest classes with complex validation rules instantly
- **Maintain perfect sync**: Your validation rules and routes automatically match your API documentation
- **Eliminate human error**: Consistent, accurate validation rules generated from your source of truth
- **Catch API drift early**: Validate that your Laravel routes match your OpenAPI specification before deployment
- **Comprehensive validation support**: All OpenAPI 3.x types, formats, and constraints mapped to Laravel validation
- **Multiple output formats**: Table, console, JSON, and HTML reports for route validation
- **CI/CD ready**: Strict mode and JSON output perfect for automated pipelines
- **Performance optimized**: Handles 100+ endpoints efficiently with caching and optimized parsing
- **Smart filtering**: Filter routes by pattern, middleware, or error type for targeted validation

Why Use This?
-------------

[](#why-use-this)

**Instead of manually writing FormRequests:** Writing validation rules for complex API endpoints is tedious and error-prone. A single endpoint with nested validation can take 15+ minutes to implement correctly.

**Instead of letting documentation drift:** Teams often update either the OpenAPI spec OR the Laravel validation rules/routes, but not both. This leads to inconsistent API behavior and broken contracts.

**Instead of manual route checking:** Manually comparing your Laravel routes against your OpenAPI specification is time-consuming and error-prone, especially with large APIs.

**For API-first development:** Generate your OpenAPI specification first, then automatically create the corresponding Laravel validation layer AND verify your routes match your contract. Your API specification becomes your single source of truth.

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

[](#installation)

### Requirements

[](#requirements)

- PHP 8.3 or higher
- Laravel 11.0 or higher
- Composer

### Install via Composer

[](#install-via-composer)

```
composer require maan511/openapi-to-laravel --dev
```

### Automatic Registration

[](#automatic-registration)

The package will automatically register the command with Laravel using auto-discovery. No manual registration is required.

Quick Start
-----------

[](#quick-start)

**1. Generate FormRequest classes from your OpenAPI specification:**

```
php artisan openapi-to-laravel:make-requests path/to/your/openapi.json
```

**All options:**

- `--output=path` - Custom output directory (default: `./app/Http/Requests`)
- `--namespace=Namespace` - Custom namespace (default: `App\Http\Requests`)
- `--force` - Overwrite existing files
- `--dry-run` - Preview without creating files (shows detailed table with class names, paths, and sizes)
- `-v|--verbose` - Show detailed output including statistics and generation progress

**2. Validate that your Laravel routes match your OpenAPI specification:**

```
php artisan openapi-to-laravel:validate-routes path/to/your/openapi.json
```

**All options:**

- `--base-path=/api` - Override server base path
- `--include-pattern="api/*"` - Only validate specific routes (can be used multiple times)
- `--exclude-middleware=web` - Exclude routes with specific middleware (can be used multiple times)
- `--ignore-route="api.health"` - Ignore specific route names/patterns (can be used multiple times)
- `--report-format=table` - Choose output format: `console`, `json`, `html`, or `table` (default: `table`)
- `--output-file=report` - Save report to file (extension auto-added based on format)
- `--strict` - Fail command on any mismatches (perfect for CI/CD)
- `--suggestions` - Include actionable fix suggestions in output
- `--filter-type=missing-documentation` - Filter by specific mismatch types (can be used multiple times)

**Available filter types:**

- `missing-documentation` - Routes implemented but not in OpenAPI spec
- `missing-implementation` - OpenAPI endpoints not implemented in Laravel
- `method-mismatch` - Same path with different HTTP methods
- `parameter-mismatch` - Different parameter requirements
- `path-mismatch` - Path pattern differences
- `validation-error` - Schema validation errors

**Next Steps:** Use your generated FormRequest classes in your Laravel controllers for automatic validation and run route validation in your CI/CD pipeline.

Supported OpenAPI Features
--------------------------

[](#supported-openapi-features)

### Schema Types

[](#schema-types)

- ✅ `object` - Generated as FormRequest with property validation (mapped to Laravel `array`)
- ✅ `array` - Generates array validation with item rules and constraints
- ✅ `string` - Maps to Laravel string validation with format support
- ✅ `integer` - Maps to Laravel integer validation
- ✅ `number` - Maps to Laravel numeric validation
- ✅ `boolean` - Maps to Laravel boolean validation

### String Formats

[](#string-formats)

All OpenAPI 3.x string formats are fully supported:

- ✅ `email` → `email` validation
- ✅ `uri`, `url` → `url` validation
- ✅ `date` → `date_format:Y-m-d` validation
- ✅ `date-time` → `date` validation
- ✅ `time` → `date_format:H:i:s` validation
- ✅ `uuid` → `uuid` validation
- ✅ `ipv4` → `ipv4` validation
- ✅ `ipv6` → `ipv6` validation
- ✅ `hostname` → Custom regex validation
- ✅ `byte` → Base64 regex validation
- ✅ `binary` → `file` validation

### Validation Constraints

[](#validation-constraints)

All OpenAPI validation keywords are mapped to Laravel rules:

**String Constraints:**

- `minLength` → `min:n`
- `maxLength` → `max:n`
- `pattern` → `regex:pattern`

**Numeric Constraints:**

- `minimum` → `min:n`
- `maximum` → `max:n`
- `multipleOf` → Custom validation

**Array Constraints:**

- `minItems` → `min:n`
- `maxItems` → `max:n`
- `uniqueItems` → `distinct`

**Object Constraints:**

- `required` → `required` validation
- `nullable` → `nullable` validation
- `minProperties` / `maxProperties` → Handled during validation

### Advanced Features

[](#advanced-features)

- ✅ **Reference Resolution**: `$ref` objects are automatically resolved from `#/components/schemas`
- ✅ **Nested Objects**: Deep nesting support with Laravel dot notation (`user.address.city`)
- ✅ **Array Items**: Array item validation with `.*` notation (`tags.*`)
- ✅ **Nested Arrays**: Support for arrays of objects (`items.*.properties`)
- ✅ **Circular Reference Detection**: Prevents infinite loops during schema resolution
- ✅ **Content Type Detection**: Supports `application/json`, `multipart/form-data`, and `application/x-www-form-urlencoded`
- ✅ **OpenAPI 3.0 &amp; 3.1**: Compatible with both OpenAPI versions
- ✅ **Nullable Handling**: Supports both OpenAPI 3.0 `nullable: true` and 3.1 type unions
- ✅ **Required Fields**: Automatically maps to Laravel `required` vs `nullable` rules
- ✅ **Multiple Schemas per Endpoint**: Handles different content types for the same endpoint

See It In Action
----------------

[](#see-it-in-action)

Transform this OpenAPI specification into a complete FormRequest class in seconds:

### OpenAPI Specification

[](#openapi-specification)

```
openapi: 3.0.0
info:
  title: User API
  version: 1.0.0
paths:
  /users:
    post:
      operationId: createUser
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                  minLength: 2
                  maxLength: 100
                email:
                  type: string
                  format: email
                age:
                  type: integer
                  minimum: 0
                  maximum: 120
                tags:
                  type: array
                  items:
                    type: string
                  minItems: 1
                  maxItems: 5
              required:
                - name
                - email
```

### Generated FormRequest

[](#generated-formrequest)

```
