> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/charlietyn/openapi-generator/llms.txt
> Use this file to discover all available pages before exploring further.

# Publishing Assets

> How to publish and customize configuration files and templates

The Laravel OpenAPI Generator service provider publishes two groups of assets: configuration files and template files. This guide explains what gets published, how to customize them, and best practices.

## Configuration Files

Publish all configuration files with a single command:

```bash theme={null}
php artisan vendor:publish --tag=openapi-config
```

### Published Files

This command publishes four configuration files to your `config/` directory:

<Accordion title="config/openapi.php">
  **Main configuration file** containing:

  * OpenAPI metadata (title, version, contact, license)
  * Server definitions for different environments
  * Security scheme definitions (Bearer, API Key, etc.)
  * Hierarchical environments for Postman/Insomnia
  * API type configurations (admin, site, mobile)
  * Module scanning paths and exclusions
  * Cache settings
  * Output path configuration
  * Model and request class paths
  * Route filtering and exclusions
  * Middleware to security mapping
  * Default response examples
  * HTTP route configuration

  **File location:** `config/openapi.php`
</Accordion>

<Accordion title="config/openapi-docs.php">
  **CRUD and entity documentation configuration** containing:

  * CRUD template definitions (summary, description, response templates)
  * Entity metadata (singular/plural names, model classes, descriptions)
  * Custom endpoint documentation
  * Auto-detection settings for fields and relationships
  * Field description overrides
  * Field example overrides

  **File location:** `config/openapi-docs.php`
</Accordion>

<Accordion title="config/openapi-templates.php">
  **Template system configuration** containing:

  * Template system enable/disable toggle
  * Template directory paths (generic and custom)
  * Generic template mappings for actions
  * Query builder documentation settings
  * Auto-detection configuration for models
  * Rendering options (debug, validation, caching)
  * Example generation settings
  * Performance limits and caching

  **File location:** `config/openapi-templates.php`
</Accordion>

<Accordion title="config/openapi-tests.php">
  **Test generation configuration** containing:

  * Test template definitions for CRUD actions
  * Test script snippets for Postman
  * Test script snippets for Insomnia
  * Custom test overrides for specific endpoints
  * Verbose logging settings

  **File location:** `config/openapi-tests.php`
</Accordion>

### Customizing Configuration

After publishing, you can customize any configuration values:

<CodeGroup>
  ```php config/openapi.php theme={null}
  // Customize API metadata
  'info' => [
      'title' => 'My Custom API',
      'description' => 'This is my amazing API',
      'version' => '2.0.0',
  ],

  // Add custom security schemes
  'security' => [
      'BearerAuth' => [
          'type' => 'http',
          'scheme' => 'bearer',
          'bearerFormat' => 'JWT',
      ],
      'OAuth2' => [
          'type' => 'oauth2',
          'flows' => [
              'authorizationCode' => [
                  'authorizationUrl' => 'https://example.com/oauth/authorize',
                  'tokenUrl' => 'https://example.com/oauth/token',
                  'scopes' => [
                      'read' => 'Read access',
                      'write' => 'Write access',
                  ],
              ],
          ],
      ],
  ],

  // Customize API types
  'api_types' => [
      'admin' => [
          'prefix' => 'admin',
          'file' => 'api.admin.php',
          'folder_name' => 'Admin API',
          'icon' => '🔒',
          'enabled' => true,
      ],
      'v2' => [
          'prefix' => 'v2',
          'file' => 'api.v2.php',
          'folder_name' => 'API v2',
          'icon' => '✨',
          'enabled' => true,
      ],
  ],
  ```
</CodeGroup>

<Info>
  Configuration changes take effect immediately. If caching is enabled, you may need to clear the cache:

  ```bash theme={null}
  php artisan cache:clear
  ```
</Info>

***

## Template Files

Publish template files separately:

```bash theme={null}
php artisan vendor:publish --tag=openapi-templates
```

### Published Template Structure

Templates are published to `resources/openapi/templates/` with the following structure:

```
resources/openapi/templates/
├── generic/
│   ├── index.json
│   ├── show.json
│   ├── store.json
│   ├── update.json
│   ├── destroy.json
│   └── ...
└── custom/
    └── (your custom endpoint templates)
```

### Template Types

<Accordion title="Generic Templates">
  **Location:** `resources/openapi/templates/generic/`

  Generic templates define documentation structure for common CRUD operations:

  * `index.json`: List/paginated collection endpoints
  * `show.json`: Single resource retrieval
  * `store.json`: Resource creation
  * `update.json`: Resource updates
  * `destroy.json`: Resource deletion

  These templates use placeholders that are automatically replaced with model-specific data during generation.

  **Example:** `generic/show.json`

  ```json theme={null}
  {
    "summary": "Get {{singular}}",
    "description": "Retrieve a single {{singular}} by ID",
    "parameters": [
      {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {"type": "integer"}
      }
    ],
    "responses": {
      "200": {
        "description": "Successful operation",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/{{model}}"
            }
          }
        }
      }
    }
  }
  ```
</Accordion>

<Accordion title="Custom Templates">
  **Location:** `resources/openapi/templates/custom/`

  Custom templates allow you to define documentation for non-CRUD endpoints or override generic templates for specific resources.

  **Example:** `custom/users_login.json`

  ```json theme={null}
  {
    "summary": "User Login",
    "description": "Authenticate a user and return an access token",
    "requestBody": {
      "required": true,
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "required": ["email", "password"],
            "properties": {
              "email": {
                "type": "string",
                "format": "email",
                "example": "user@example.com"
              },
              "password": {
                "type": "string",
                "format": "password",
                "example": "secret123"
              }
            }
          }
        }
      }
    },
    "responses": {
      "200": {
        "description": "Login successful",
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "properties": {
                "token": {"type": "string"},
                "user": {"$ref": "#/components/schemas/User"}
              }
            }
          }
        }
      },
      "401": {
        "description": "Invalid credentials"
      }
    }
  }
  ```
</Accordion>

### Template Placeholders

Templates support automatic placeholder replacement:

| Placeholder         | Replaced With        | Example                   |
| ------------------- | -------------------- | ------------------------- |
| `{{model}}`         | Model class name     | `User`                    |
| `{{singular}}`      | Singular entity name | `user`                    |
| `{{plural}}`        | Plural entity name   | `users`                   |
| `{{table}}`         | Database table name  | `users`                   |
| `{{primaryKey}}`    | Primary key field    | `id`                      |
| `{{fields}}`        | Model fields         | Auto-generated from model |
| `{{relationships}}` | Model relationships  | Auto-generated from model |

<Info>
  Placeholders are automatically extracted from your models using reflection and database schema inspection.
</Info>

***

## Publishing Workflow

### Initial Setup

When setting up a new project:

```bash theme={null}
# 1. Install the package
composer require ronu/laravel-openapi-generator

# 2. Publish configuration files
php artisan vendor:publish --tag=openapi-config

# 3. (Optional) Publish templates if you need customization
php artisan vendor:publish --tag=openapi-templates

# 4. Customize configuration
vim config/openapi.php

# 5. Generate documentation
php artisan openapi:generate
```

### Updating Published Assets

When updating the package to a new version:

<Warning>
  Publishing again will overwrite your customized files. Back up your changes first.
</Warning>

```bash theme={null}
# Backup existing config
cp config/openapi.php config/openapi.php.backup

# Re-publish
php artisan vendor:publish --tag=openapi-config --force

# Compare and merge changes
diff config/openapi.php.backup config/openapi.php
```

**Better approach:** Use version control and selectively merge new options:

```bash theme={null}
# See what changed in the package
git diff vendor/ronu/laravel-openapi-generator/config/

# Manually add new config options to your published files
```

***

## File Locations Reference

### Configuration Files

| File                    | Location                       | Purpose              |
| ----------------------- | ------------------------------ | -------------------- |
| `openapi.php`           | `config/openapi.php`           | Main configuration   |
| `openapi-docs.php`      | `config/openapi-docs.php`      | CRUD and entity docs |
| `openapi-templates.php` | `config/openapi-templates.php` | Template system      |
| `openapi-tests.php`     | `config/openapi-tests.php`     | Test generation      |

### Template Files

| Directory         | Location                               | Purpose                   |
| ----------------- | -------------------------------------- | ------------------------- |
| Generic templates | `resources/openapi/templates/generic/` | CRUD templates            |
| Custom templates  | `resources/openapi/templates/custom/`  | Custom endpoint templates |

### Generated Output

| Type                 | Location                               | Description              |
| -------------------- | -------------------------------------- | ------------------------ |
| OpenAPI specs        | `storage/app/public/openapi/openapi/`  | JSON/YAML specifications |
| Postman collections  | `storage/app/public/openapi/postman/`  | Postman collection files |
| Insomnia collections | `storage/app/public/openapi/insomnia/` | Insomnia workspace files |

<Info>
  Output location can be customized via the `openapi.output_path` configuration option.
</Info>

***

## Advanced Customization

### Custom Security Schemes

Add OAuth2, OpenID Connect, or custom authentication:

```php config/openapi.php theme={null}
'security' => [
    'OAuth2' => [
        'type' => 'oauth2',
        'flows' => [
            'authorizationCode' => [
                'authorizationUrl' => 'https://auth.example.com/authorize',
                'tokenUrl' => 'https://auth.example.com/token',
                'refreshUrl' => 'https://auth.example.com/refresh',
                'scopes' => [
                    'read:users' => 'Read user data',
                    'write:users' => 'Modify user data',
                    'admin' => 'Administrative access',
                ],
            ],
        ],
    ],
],

'middleware_security_map' => [
    'auth:sanctum' => ['BearerAuth'],
    'oauth' => ['OAuth2'],
    'scopes:admin' => ['OAuth2'],
],
```

### Multiple API Versions

Document multiple API versions simultaneously:

```php config/openapi.php theme={null}
'api_types' => [
    'v1' => [
        'prefix' => 'v1',
        'file' => 'api.v1.php',
        'description' => 'API Version 1 (Deprecated)',
        'folder_name' => 'API v1',
        'icon' => '📦',
        'middleware' => ['api', 'api.v1'],
        'enabled' => true,
    ],
    'v2' => [
        'prefix' => 'v2',
        'file' => 'api.v2.php',
        'description' => 'API Version 2 (Current)',
        'folder_name' => 'API v2',
        'icon' => '✨',
        'middleware' => ['api'],
        'enabled' => true,
    ],
],
```

### Custom Response Schemas

Add custom response schemas for your API:

```php config/openapi.php theme={null}
'response_examples' => [
    '200' => [
        'description' => 'Successful operation',
        'content' => [
            'application/json' => [
                'schema' => [
                    'type' => 'object',
                    'properties' => [
                        'success' => ['type' => 'boolean', 'example' => true],
                        'data' => ['type' => 'object'],
                        'meta' => [
                            'type' => 'object',
                            'properties' => [
                                'timestamp' => ['type' => 'string', 'format' => 'date-time'],
                                'request_id' => ['type' => 'string'],
                            ],
                        ],
                    ],
                ],
            ],
        ],
    ],
],
```

### Environment-Specific Servers

Define servers for different deployment environments:

```php config/openapi.php theme={null}
'servers' => [
    [
        'url' => 'http://localhost:8000',
        'description' => 'Local Development',
    ],
    [
        'url' => 'https://staging-api.mycompany.com',
        'description' => 'Staging Environment',
    ],
    [
        'url' => 'https://api.mycompany.com',
        'description' => 'Production Environment',
    ],
],
```

***

## Best Practices

<Accordion title="Version Control">
  **Commit published files to version control:**

  ```bash theme={null}
  git add config/openapi*.php
  git add resources/openapi/templates/
  git commit -m "Add OpenAPI configuration"
  ```

  This ensures all team members use the same configuration.
</Accordion>

<Accordion title="Environment-Specific Overrides">
  **Use `.env` for environment-specific values:**

  ```php config/openapi.php theme={null}
  'info' => [
      'title' => env('APP_NAME', 'Laravel API'),
      'version' => env('API_VERSION', '1.0.0'),
  ],
  ```

  Then set different values per environment:

  ```bash .env.production theme={null}
  APP_NAME="Production API"
  API_VERSION=2.0.0
  ```
</Accordion>

<Accordion title="Selective Publishing">
  **Publish only what you need:**

  ```bash theme={null}
  # Publish only configuration (most common)
  php artisan vendor:publish --tag=openapi-config

  # Publish templates only if you need customization
  php artisan vendor:publish --tag=openapi-templates
  ```

  You don't need to publish templates unless you're customizing them.
</Accordion>

<Accordion title="Documentation">
  **Document your customizations:**

  Add comments to your config files explaining custom settings:

  ```php config/openapi.php theme={null}
  // Custom security scheme for our OAuth2 provider
  'security' => [
      'OAuth2' => [
          // Configuration for Auth0 integration
          'type' => 'oauth2',
          // ...
      ],
  ],
  ```
</Accordion>

<Accordion title="Template Inheritance">
  **Use custom templates sparingly:**

  Only create custom templates when generic templates don't fit. This reduces maintenance burden when the package is updated.

  Good:

  ```
  custom/
  └── users_login.json  (truly custom endpoint)
  ```

  Avoid:

  ```
  custom/
  ├── users_index.json  (could use generic/index.json)
  ├── users_show.json   (could use generic/show.json)
  └── users_store.json  (could use generic/store.json)
  ```
</Accordion>

***

## Troubleshooting

<Accordion title="Config files not updating">
  **Problem:** Changes to config files don't take effect.

  **Solution:** Clear configuration cache:

  ```bash theme={null}
  php artisan config:clear
  php artisan cache:clear
  ```
</Accordion>

<Accordion title="Templates not found">
  **Problem:** Generator can't find custom templates.

  **Solution:** Verify template paths in `config/openapi-templates.php`:

  ```php theme={null}
  'paths' => [
      'generic' => resource_path('openapi/templates/generic'),
      'custom' => resource_path('openapi/templates/custom'),
  ],
  ```

  Ensure directories exist:

  ```bash theme={null}
  mkdir -p resources/openapi/templates/{generic,custom}
  ```
</Accordion>

<Accordion title="Publishing overwrites customizations">
  **Problem:** Re-publishing overwrites your changes.

  **Solution:** Use version control and selective merging:

  ```bash theme={null}
  # Before re-publishing
  git commit -am "Backup current config"

  # Re-publish with force
  php artisan vendor:publish --tag=openapi-config --force

  # Review and merge
  git diff HEAD~1
  ```
</Accordion>
