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

ActiveLibrary[API Development](/categories/api)

herolabid/laravel-openapi
=========================

Modern OpenAPI 3.1 documentation generator for Laravel 11+ using PHP 8.2+ attributes. Zero config, smart caching, auto-detects modules, FormRequests, and API Resources.

00PHP

Since Jan 17Pushed 3mo agoCompare

[ Source](https://github.com/herolabid/laravel-openapi)[ Packagist](https://packagist.org/packages/herolabid/laravel-openapi)[ RSS](/packages/herolabid-laravel-openapi/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel OpenAPI
===============

[](#laravel-openapi)

**Modern OpenAPI 3.1 documentation generator for Laravel 11+.**

A next-generation approach to API documentation using PHP 8.2+ attributes, replacing annotation-based tools with native language features. Built for developer experience with zero configuration, smart caching, and automatic module detection.

Features
--------

[](#features)

### Core Features

[](#core-features)

- **Zero Configuration** - Works out of the box with sensible defaults
- **PHP 8.2+ Attributes** - Native attribute-based syntax, no DocBlock annotations
- **Smart Caching** - 10x faster with intelligent file change detection
- **Dual UI Support** - Both Swagger UI and ReDoc included
- **Hot Reload** - Auto-regenerate specs during development

### Laravel Integration

[](#laravel-integration)

- **Modular Architecture** - Auto-detects nwdart/laravel-modules and custom module structures
- **Auto-detect Security** - Automatically detects Laravel Sanctum and Passport configurations
- **FormRequest Integration** - Generate request schemas from validation rules
- **API Resource Support** - Extract response schemas from API Resources

### Code Quality

[](#code-quality)

- **Clean Architecture** - SOLID principles and layered design
- **Well Tested** - 80%+ test coverage
- **Minimal Dependencies** - Lightweight and focused

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 11.0 or higher

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

[](#installation)

```
composer require herolabid/laravel-openapi
```

That's it! The package auto-registers via Laravel's package discovery.

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

[](#quick-start)

### 1. Add Attributes to Your Controllers

[](#1-add-attributes-to-your-controllers)

```
use App\Models\User;
use HerolabID\LaravelOpenApi\Attributes\{Get, Response, Parameter};

class UserController extends Controller
{
    #[Get(
        path: '/api/users/{id}',
        summary: 'Get user by ID',
        tags: ['Users']
    )]
    #[Parameter(
        name: 'id',
        in: 'path',
        required: true,
        schema: ['type' => 'integer']
    )]
    #[Response(
        status: 200,
        description: 'User found',
        content: new Schema(ref: User::class)
    )]
    public function show(string $id)
    {
        return User::findOrFail($id);
    }
}
```

### 2. View Documentation

[](#2-view-documentation)

Visit your API documentation:

- **Swagger UI**: `http://your-app.test/api/docs/swagger`
- **ReDoc**: `http://your-app.test/api/docs/redoc`
- **JSON Spec**: `http://your-app.test/api/docs/spec.json`
- **YAML Spec**: `http://your-app.test/api/docs/spec.yaml`

### 3. Generate Spec (Optional)

[](#3-generate-spec-optional)

```
php artisan openapi:generate
```

The spec is automatically generated on first request, but you can pre-generate it for production.

Configuration
-------------

[](#configuration)

Publish the config file (optional):

```
php artisan vendor:publish --tag=openapi-config
```

Default configuration (`config/openapi.php`):

```
return [
    'info' => [
        'title' => env('APP_NAME', 'API Documentation'),
        'version' => '1.0.0',
    ],

    'scan' => [
        'controllers' => [app_path('Http/Controllers')],
        'models' => [app_path('Models')],
    ],

    'modules' => [
        'enabled' => true,
        'auto_detect' => true,  // Auto-detect nwdart/laravel-modules
        'paths' => [],           // Custom module paths
    ],

    'cache' => [
        'enabled' => !app()->environment('local'),
        'ttl' => 3600,
    ],

    'hot_reload' => app()->environment('local'),

    'ui' => [
        'swagger' => true,
        'redoc' => true,
        'route_prefix' => 'api/docs',
    ],
];
```

### Modular Architecture Support

[](#modular-architecture-support)

The package automatically detects and scans **nwdart/laravel-modules** and other modular structures.

#### Auto-Detection (nwdart/laravel-modules)

[](#auto-detection-nwdartlaravel-modules)

If you're using [nwdart/laravel-modules](https://github.com/nWidart/laravel-modules), the package will **automatically** discover all your modules:

```
// config/openapi.php
'modules' => [
    'enabled' => true,
    'auto_detect' => true,  // ✅ Enabled by default
],
```

**Example structure:**

```
Modules/
├── User/
│   ├── Http/Controllers/UserController.php  ✅ Auto-discovered
│   └── Models/User.php                      ✅ Auto-discovered
├── Product/
│   ├── Http/Controllers/ProductController.php
│   └── Entities/Product.php                 ✅ Supports "Entities" folder
└── Order/
    ├── Controllers/OrderController.php      ✅ Alternative structure
    └── Models/Order.php

```

#### Custom Modular Paths

[](#custom-modular-paths)

For custom module structures (not using nwdart), specify paths manually:

```
// config/openapi.php
'modules' => [
    'enabled' => true,
    'auto_detect' => false,
    'paths' => [
        base_path('modules'),
        base_path('app/Modules'),
    ],
    'scan_paths' => [
        'controllers' => ['Http/Controllers', 'Controllers'],
        'models' => ['Models', 'Entities'],
    ],
],
```

#### Disable Module Scanning

[](#disable-module-scanning)

If you don't use modules, you can disable it:

```
'modules' => [
    'enabled' => false,
],
```

### Laravel FormRequest Integration

[](#laravel-formrequest-integration)

Automatically generate request body schemas from FormRequest validation rules:

```
use Illuminate\Foundation\Http\FormRequest;

class CreateUserRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'age' => 'integer|min:18|max:100',
            'role' => 'required|in:admin,user,guest',
        ];
    }
}
```

The package automatically converts validation rules to OpenAPI schema:

```
CreateUserRequest:
  type: object
  required: [name, email, role]
  properties:
    name:
      type: string
      maxLength: 255
    email:
      type: string
      format: email
    age:
      type: integer
      minimum: 18
      maximum: 100
    role:
      type: string
      enum: [admin, user, guest]
```

### API Resource Integration

[](#api-resource-integration)

Extract response schemas from Laravel API Resources:

```
use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
        ];
    }
}
```

Automatically generates response schema with proper structure.

Artisan Commands
----------------

[](#artisan-commands)

```
# Generate OpenAPI spec
php artisan openapi:generate

# Clear cached spec
php artisan openapi:clear

# Validate spec
php artisan openapi:validate

# Serve with hot reload
php artisan openapi:serve
```

Available Attributes
--------------------

[](#available-attributes)

### Operation Attributes

[](#operation-attributes)

```
#[Get(path: '/api/users', summary: 'List users')]
#[Post(path: '/api/users', summary: 'Create user')]
#[Put(path: '/api/users/{id}', summary: 'Update user')]
#[Patch(path: '/api/users/{id}', summary: 'Partial update')]
#[Delete(path: '/api/users/{id}', summary: 'Delete user')]
```

### Parameter Attributes

[](#parameter-attributes)

```
#[Parameter(
    name: 'id',
    in: 'path',
    required: true,
    schema: ['type' => 'integer']
)]

#[Parameter(
    name: 'filter',
    in: 'query',
    schema: ['type' => 'string']
)]
```

### Request Body

[](#request-body)

```
#[RequestBody(
    description: 'User data',
    required: true,
    content: new Schema(ref: User::class)
)]
```

### Response Attributes

[](#response-attributes)

```
#[Response(
    status: 200,
    description: 'Success',
    content: new Schema(ref: User::class)
)]

#[Response(
    status: 404,
    description: 'Not found'
)]
```

### Schema Attributes (for Models)

[](#schema-attributes-for-models)

```
use HerolabID\LaravelOpenApi\Attributes\{Schema, Property};

#[Schema(title: 'User', description: 'User model')]
class User extends Model
{
    #[Property(type: 'integer', example: 1)]
    public int $id;

    #[Property(type: 'string', example: 'John Doe')]
    public string $name;

    #[Property(type: 'string', format: 'email')]
    public string $email;
}
```

Architecture
------------

[](#architecture)

This package follows clean code principles and layered architecture:

```
┌─────────────────────────────────────────────┐
│     Presentation Layer (UI, Controllers)     │
├─────────────────────────────────────────────┤
│   Application Layer (Commands, Services)    │
├─────────────────────────────────────────────┤
│      Domain Layer (Attributes, Builders)     │
├─────────────────────────────────────────────┤
│  Infrastructure Layer (Cache, File I/O)     │
└─────────────────────────────────────────────┘

```

### Key Design Patterns

[](#key-design-patterns)

- **Builder Pattern** - Spec generation
- **Strategy Pattern** - Multiple UI renderers
- **Repository Pattern** - Cache access
- **Factory Pattern** - Parser creation
- **Dependency Injection** - All services use constructor injection

Performance
-----------

[](#performance)

- **First generation**: &lt; 500ms for 50 routes
- **Cached retrieval**: &lt; 10ms
- **Hot reload detection**: &lt; 50ms
- **Memory usage**: &lt; 10MB

Approximately **10x faster** than L5-Swagger with caching enabled.

Development
-----------

[](#development)

```
# Install dependencies
composer install

# Run tests
composer test

# Run tests with coverage
composer test-coverage

# Static analysis
composer analyse

# Code formatting
composer format
```

Testing
-------

[](#testing)

This package maintains 80%+ test coverage with:

- **Unit Tests** - Individual class testing
- **Integration Tests** - Multi-component testing
- **Feature Tests** - End-to-end testing

```
composer test
```

Code Quality
------------

[](#code-quality-1)

- PHPStan Level 8
- PSR-12 Code Style
- SOLID Principles
- Comprehensive PHPDoc

Why Choose Laravel OpenAPI?
---------------------------

[](#why-choose-laravel-openapi)

### vs L5-Swagger

[](#vs-l5-swagger)

FeatureL5-SwaggerLaravel OpenAPISyntaxDocBlock annotationsPHP 8.2+ AttributesConfig Lines318~50Dependencies5+ packages2 core packagesInstallationMulti-step processSingle commandCachingManualSmart + Auto-invalidationHot ReloadNoYesUI OptionsSwagger onlySwagger + ReDocModule SupportManual configAuto-detectionFormRequestNoAuto-generate schemasAPI ResourceNoAuto-extract schemasSecurity DetectionManualAuto (Sanctum/Passport)### Key Advantages

[](#key-advantages)

1. **Native PHP Attributes** - No external annotation syntax, just PHP
2. **Zero Config** - Works immediately after installation
3. **Smart Caching** - Automatically invalidates when files change
4. **Module-Aware** - Detects nwdart/laravel-modules automatically
5. **Laravel-Native** - Deep integration with FormRequests and Resources

Roadmap
-------

[](#roadmap)

### Completed ✓

[](#completed-)

- Core attribute system
- OpenAPI 3.1 spec generation
- Dual UI (Swagger + ReDoc)
- Smart caching with auto-invalidation
- Modular architecture support
- Security auto-detection
- FormRequest schema generation
- API Resource schema extraction

### Planned

[](#planned)

- Request/Response examples from tests
- Interactive API playground
- Improved type inference
- Enhanced validation rules parsing

Contributing
------------

[](#contributing)

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- **Author**: Irfan Arsyad
- **Inspired by**: L5-Swagger

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

19

—

LowBetter than 10% of packages

Maintenance56

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/bc01642f81607ec82e4239c7974f69daa17ee38d152bce69580c8628a70e1057?d=identicon)[Irfan Hukama Arsyad](/maintainers/Irfan%20Hukama%20Arsyad)

---

Top Contributors

[![IrfanArsyad](https://avatars.githubusercontent.com/u/4258537?v=4)](https://github.com/IrfanArsyad "IrfanArsyad (5 commits)")

### Embed Badge

![Health badge](/badges/herolabid-laravel-openapi/health.svg)

```
[![Health](https://phpackages.com/badges/herolabid-laravel-openapi/health.svg)](https://phpackages.com/packages/herolabid-laravel-openapi)
```

###  Alternatives

[stripe/stripe-php

Stripe PHP Library

4.0k143.3M475](/packages/stripe-stripe-php)[twilio/sdk

A PHP wrapper for Twilio's API

1.6k92.9M270](/packages/twilio-sdk)[knplabs/github-api

GitHub API v3 client

2.2k15.8M187](/packages/knplabs-github-api)[facebook/php-business-sdk

PHP SDK for Facebook Business

90121.9M34](/packages/facebook-php-business-sdk)[meilisearch/meilisearch-php

PHP wrapper for the Meilisearch API

73813.7M114](/packages/meilisearch-meilisearch-php)[google/gax

Google API Core for PHP

263103.1M452](/packages/google-gax)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
