Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

L5 Swagger Laravel Package

darkaonline/l5-swagger

Laravel-friendly wrapper around swagger-php and Swagger UI. Generate and serve OpenAPI/Swagger docs from annotations, with configurable routes, UI, and assets. Includes install/config guides, migration notes, tips, and Passport auth examples.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require darkaonline/l5-swagger
    php artisan vendor:publish --provider="DarkaOnLine\L5Swagger\L5SwaggerServiceProvider" --tag=l5-swagger-config
    

    Publish the config file to config/l5-swagger.php.

  2. Basic Configuration: Update .env with your API base path:

    L5_SWAGGER_FORMAT=json
    
  3. First Use Case: Add OpenAPI attributes to a controller method:

    use DarkaOnLine\L5Swagger\Annotations as SWG;
    
    class UserController extends Controller
    {
        /**
         * @SWG\Get(
         *     path="/users",
         *     summary="Get all users",
         *     @SWG\Response(response=200, description="List of users")
         * )
         */
        public function index()
        {
            return User::all();
        }
    }
    

    Access Swagger UI at /api/documentation.


Implementation Patterns

Core Workflows

  1. Annotation-Based Documentation: Use PHP attributes (or annotations) to define API endpoints, parameters, and responses:

    /**
     * @SWG\Post(
     *     path="/users",
     *     summary="Create a user",
     *     @SWG\Parameter(
     *         in="body",
     *         name="user",
     *         required=true,
     *         @SWG\Schema(ref="#/definitions/User")
     *     ),
     *     @SWG\Response(response=201, description="User created")
     * )
     */
    public function store(Request $request)
    {
        // ...
    }
    
  2. Dynamic API Definition: Generate OpenAPI specs programmatically in service providers or bootstrappers:

    public function boot()
    {
        $openapi = \OpenApi\Generator::scan([app_path('Http/Controllers')]);
        file_put_contents(public_path('openapi.json'), $openapi->toJson());
    }
    
  3. Swagger UI Customization: Extend the default UI via config/l5-swagger.php:

    'ui' => [
        'display' => [
            'deep_linking' => true,
            'doc_expansion' => 'none',
        ],
        'theme' => 'dark',
    ],
    
  4. Authentication Integration: Configure OAuth2/Passport in config/l5-swagger.php:

    'securityDefinitions' => [
        'bearerAuth' => [
            'type' => 'apiKey',
            'name' => 'Authorization',
            'in' => 'header',
        ],
    ],
    

Integration Tips

  • Middleware: Use L5Swagger\Middleware\Documentation to exclude routes from Swagger generation:
    Route::middleware(['api', 'documentation:ignore'])->group(function () {
        // Routes to exclude
    });
    
  • Testing: Mock Swagger responses in tests:
    $this->get('/api/documentation')
         ->assertSee('Get all users');
    
  • Multi-API Projects: Use swagger_ui view to merge multiple OpenAPI specs:
    return view('swagger-ui', [
        'specs' => [
            ['url' => '/api/v1/documentation', 'label' => 'API v1'],
            ['url' => '/api/v2/documentation', 'label' => 'API v2'],
        ],
    ]);
    

Gotchas and Tips

Common Pitfalls

  1. Annotation Parsing Issues:

    • Symptom: Annotations ignored or misparsed.
    • Fix: Ensure swagger-php processors are correctly configured in config/l5-swagger.php:
      'processors' => [
          'DarkaOnLine\L5Swagger\Processors\Annotations',
          'DarkaOnLine\L5Swagger\Processors\Attributes',
      ],
      
    • Tip: Use php artisan l5-swagger:generate to regenerate specs after changes.
  2. Caching Conflicts:

    • Symptom: Outdated Swagger UI or API specs.
    • Fix: Clear cached views and specs:
      php artisan view:clear
      php artisan cache:clear
      
  3. Environment-Specific Configs:

    • Symptom: Config overrides not applied in staging/production.
    • Fix: Use environment variables for critical settings (e.g., L5_SWAGGER_FORMAT):
      L5_SWAGGER_FORMAT=json  # Override config value
      
  4. PHP Attributes vs. Annotations:

    • Gotcha: Laravel 8+ uses PHP 8 attributes (#[SWG\Get]), while older versions rely on docblocks.
    • Fix: Install doctrine/annotations for backward compatibility:
      composer require doctrine/annotations
      

Debugging Tips

  • Log Generation: Enable debug logs in config/l5-swagger.php:

    'debug' => true,
    

    Logs appear in storage/logs/l5-swagger.log.

  • Validate Specs: Use the Swagger Validator to test generated specs:

    php artisan l5-swagger:validate
    
  • Asset Paths: Ensure L5_SWAGGER_UI_ASSETS_PATH in .env points to a valid directory:

    L5_SWAGGER_UI_ASSETS_PATH=public/swagger-ui
    

Extension Points

  1. Custom Processors: Extend DarkaOnLine\L5Swagger\Processors\BaseProcessor to add custom logic (e.g., for GraphQL or gRPC).

  2. Swagger UI Themes: Override the default theme by publishing assets:

    php artisan vendor:publish --tag=l5-swagger-assets
    

    Then customize resources/views/vendor/l5-swagger/swagger-ui.blade.php.

  3. API Versioning: Use route groups to isolate Swagger specs by version:

    Route::prefix('api/v1')->group(function () {
        // v1 routes with @SWG\Tag(name="v1")
    });
    
  4. Security Schemes: Dynamically add OAuth2/Passport schemes via service providers:

    $this->app->singleton(\OpenApi\Annotations\OpenApi::class, function () {
        $openapi = new \OpenApi\Annotations\OpenApi();
        $openapi->securitySchemes = [
            'bearerAuth' => [
                'type' => 'http',
                'scheme' => 'bearer',
                'bearerFormat' => 'JWT',
            ],
        ];
        return $openapi;
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope