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

Scramble Laravel Package

dedoc/scramble

Scramble generates up-to-date OpenAPI 3.1 API docs for Laravel automatically from your code—no PHPDoc annotations needed. Adds /docs/api UI and /docs/api.json schema routes (local by default, configurable via gate).

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation** (updated for v0.13.33):
   ```bash
   composer require dedoc/scramble:^0.13.33

Publish the config file (optional):

php artisan vendor:publish --provider="Dedoc\Scramble\ScrambleServiceProvider" --tag="scramble-config"
  1. First Use Case (enhanced with new CLI command):

    • Access /docs/api in your local environment to view the auto-generated OpenAPI documentation UI.
    • Access /docs/api.json to fetch the raw OpenAPI spec in JSON format.
    • New: Generate documentation via CLI:
      php artisan scramble:generate
      
  2. Environment Check (updated for stricter defaults): Ensure the viewApiDocs gate is configured. New release enforces stricter environment checks by default:

    Gate::define('viewApiDocs', fn () => in_array(app()->environment(), config('scramble.environment', ['local'])));
    

Implementation Patterns

Core Workflow (updated with new features)

  1. Route Documentation (enhanced with middleware support): Scramble now auto-detects middleware groups and documents them:

    // Auto-documented route with middleware
    Route::middleware(['auth:sanctum', 'throttle:60'])->group(function () {
        Route::get('/profile', [ProfileController::class, 'show']);
    });
    
  2. Controller Methods (new response type inference): Scramble now better handles Laravel's JsonResponse and Response facade:

    // Auto-documented with Response facade
    public function customResponse(): Response
    {
        return response()->json(['data' => 'value']);
    }
    
  3. Request Validation (enhanced with nested rule support): Scramble now properly documents deeply nested validation rules:

    public function rules(): array
    {
        return [
            'user.address.city' => ['required', 'string'],
            'user.address.coordinates' => ['array', 'min:2'],
            'user.address.coordinates.*' => ['numeric'],
        ];
    }
    
  4. Response Types (new collection handling): Scramble now better handles Collection responses with custom formatting:

    public function index(): Collection
    {
        return User::all();
    }
    
  5. Customization via Attributes (new attributes):

    use Dedoc\Scramble\Attributes\{Endpoint, Schema, Parameter, Deprecated};
    
    #[Endpoint(
        title: 'Custom Title',
        description: 'Custom description',
        security: ['bearerAuth']
    )]
    #[Deprecated(since: 'v1.0.0', reason: 'Use new endpoint instead')]
    public function legacyEndpoint(): void {}
    

Integration Tips (updated)

  • API Resources (enhanced with JSON:API 1.1 support):

    // Auto-documented JSON:API resource
    public function toArray($request): array
    {
        return [
            'data' => [
                'type' => 'users',
                'id' => $this->id,
                'attributes' => [
                    'name' => $this->name,
                    'email' => $this->email,
                ],
                'relationships' => [
                    'posts' => [
                        'data' => $this->posts->map(fn ($post) => ['id' => $post->id, 'type' => 'posts']),
                    ],
                ],
            ],
        ];
    }
    
  • Authentication (new security scheme support):

    // Configure security schemes in config/scramble.php
    'security_schemes' => [
        'bearerAuth' => [
            'type' => 'http',
            'scheme' => 'bearer',
            'bearerFormat' => 'JWT',
        ],
        'apiKeyAuth' => [
            'type' => 'apiKey',
            'name' => 'X-API-KEY',
            'in' => 'header',
        ],
    ],
    
  • Filtering Routes (new pattern matching):

    'api_path' => [
        'include' => [
            'api/v1/*',
            'api/v2/users/*',
        ],
        'exclude' => [
            'api/v1/legacy/*',
            'api/v2/admin/*',
        ],
        'prefix' => 'api', // New: auto-prefix matching
    ],
    
  • Caching (enhanced with cache tags):

    'cache' => [
        'enabled' => true,
        'ttl' => 60,
        'tags' => ['api-docs'], // New: cache tag support
    ],
    

Gotchas and Tips

Common Pitfalls (updated)

  1. Environment Restrictions (stricter defaults):

    • New release enforces stricter environment checks. Update your config:
      'environment' => ['local', 'staging'], // Explicitly allow environments
      
  2. Complex Type Inference (new handling for generics):

    • Scramble now better handles generic types but may still struggle with:
      #[Schema(type: 'array', items: new \OpenApi\Schemas\GenericItemSchema())]
      public function getGenericData(): array {}
      
  3. Facade and Static Calls (new handling for Response facade):

    • The Response facade is now auto-documented, but complex static calls may need:
      #[IgnoreParam]
      public function complexStaticCall(): \Illuminate\Http\Response {}
      
  4. Validation Rule Quirks (new nested rule support):

    • Custom nested validation rules may still need explicit documentation:
      #[Schema(
          type: 'object',
          properties: [
              'user' => new \OpenApi\Schemas\ObjectSchema([
                  'properties' => [
                      'address' => new \OpenApi\Schemas\ObjectSchema([
                          'properties' => [
                              'city' => new \OpenApi\Schemas\StringSchema(),
                          ],
                      ]),
                  ],
              ]),
          ]
      )]
      public function rules(): array {}
      
  5. Memory Leaks (new cache invalidation):

    • Large projects should use cache invalidation:
      php artisan cache:forget api-docs
      

Debugging Tips (updated)

  • Inspect Raw Spec (new validation): Access /docs/api.json and validate with:

    php artisan scramble:validate
    
  • Log Analysis (enhanced logging): Enable debug logging in config/scramble.php:

    'debug' => [
        'enabled' => true,
        'level' => 'verbose', // New: verbose logging level
    ],
    
  • Attribute Overrides (new attributes):

    #[Endpoint(hidden: true)] // New: hide entire endpoint
    public function secretMethod(): void {}
    
    #[Parameter(explode: true)] // New: explode query parameters
    public function filterRequest(string $filter): void {}
    

Extension Points (updated)

  1. Custom Extensions (new schema extension points):

    Scramble::extendSchema(function (Schema $schema, string $class) {
        if (is_a($class, JsonApiResource::class, true)) {
            $schema->property('links', new \OpenApi\Schemas\ObjectSchema());
        }
    });
    
  2. Event Listeners (new events):

    Scramble::listen(ScrambleGenerated::class, function (ScrambleGenerated $event) {
        $event->spec->servers = [
            ['url' => 'https://api.example.com/v1', 'description' => 'Production'],
            ['url' => 'https://staging.api.example.com/v1', 'description' => 'Staging'],
        ];
    });
    
    // New: ScrambleValidating event
    Scramble::listen(ScrambleValidating::class, function (ScrambleValidating $event) {
        if (!$event->isValid()) {
            // Handle validation errors
        }
    });
    
  3. Rule Evaluation (new rule evaluator):

    Scramble::extendRuleEvaluator(new class implements RuleEvaluator {
        public function evaluate(string $rule, mixed $value, array $parameters = []): bool {
            // Handle custom rules like 'unique:users,email'
            return true;
        }
    });
    
  4. UI Customization (new template hooks):

    • Publish assets and customize:
      php artisan vendor:publish --provider="Dedoc\Scramble\ScrambleServiceProvider" --tag="scramble-assets"
      
    • Override resources/views/vendor/scramble/partials/header.blade.php for custom headers.

Pro Tips (updated)

  • Laravel 13+ Compatibility (enhanced): Scramble now fully supports Laravel 13.x with:
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.
bugban/php-sdk
littlerocket/job-queue-bundle
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/opensearch-client
directorytree/opensearch-adapter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php