PHP code example of wadakatu / laravel-spectrum

1. Go to this page and download the library: Download wadakatu/laravel-spectrum library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wadakatu / laravel-spectrum example snippets


// app/Http/Requests/StoreUserRequest.php
class StoreUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => '|max:120',
            'roles' => 'array',
            'roles.*' => 'exists:roles,id',
        ];
    }

    public function messages()
    {
        return [
            'email.unique' => 'This email is already registered.',
        ];
    }
}

// Controller - automatically documented!
public function store(StoreUserRequest $request)
{
    $user = User::create($request->validated());
    return new UserResource($user);
}

// app/Http/Resources/UserResource.php
class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'email_verified' => $this->email_verified_at !== null,
            'roles' => RoleResource::collection($this->whenLoaded('roles')),
            'created_at' => $this->created_at->toDateTimeString(),
            'profile' => new ProfileResource($this->whenLoaded('profile')),
        ];
    }
}

// app/Transformers/UserTransformer.php
class UserTransformer extends TransformerAbstract
{
    protected $availableIncludes = ['posts', 'profile', 'followers'];
    protected $defaultIncludes = ['profile'];
    
    public function transform(User $user)
    {
        return [
            'id' => (int) $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'member_since' => $user->created_at->toDateString(),
            'is_active' => (bool) $user->is_active,
        ];
    }
    
    public function 

// Lumen Controller with inline validation
public function store(Request $request)
{
    // Automatically detected and documented!
    $this->validate($request, [
        'title' => 'create($request->all());
    
    return $this->fractal->item($post, new PostTransformer());
}

// Automatically detects authentication methods
Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('users', UserController::class);
});

// API Key authentication
Route::middleware('auth.apikey')->group(function () {
    Route::get('/stats', StatsController::class);
});

// config/spectrum.php
return [
    // API Information
    'title' => env('APP_NAME', 'Laravel API'),
    'version' => '1.0.0',
    'description' => 'API Documentation',
    
    // Server Configuration
    'servers' => [
        [
            'url' => env('APP_URL'),
            'description' => 'Production server',
        ],
    ],
    
    // Route Detection
    'route_patterns' => [
        'api/*',        // Include all /api routes
        'api/v1/*',     // Version-specific routes
        'api/v2/*',
    ],
    
    'excluded_routes' => [
        'api/health',   // Exclude health checks
        'api/debug/*',  // Exclude debug endpoints
    ],
    
    // Response Formats
    'response_formats' => [
        'resource' => true,     // Laravel Resources
        'fractal' => true,      // Fractal Transformers
        'json' => true,         // Plain JSON responses
    ],
    
    // Security Schemes
    'security_schemes' => [
        'bearer' => [
            'type' => 'http',
            'scheme' => 'bearer',
            'bearerFormat' => 'JWT',
        ],
        'apiKey' => [
            'type' => 'apiKey',
            'in' => 'header',
            'name' => 'X-API-Key',
        ],
    ],
    
    // Tag Mappings for Organizing Endpoints
    'tags' => [
        // Exact match
        'api/v1/auth/login' => 'Authentication',
        'api/v1/auth/logout' => 'Authentication',
        
        // Wildcard patterns
        'api/v1/auth/*' => 'Authentication',
        'api/v1/admin/*' => 'Administration',
        'api/v1/billing/*' => 'Billing',
        'api/v1/users/*' => 'User Management',
    ],
    
    // Cache Configuration
    'cache' => [
        'enabled' => env('SPECTRUM_CACHE_ENABLED', true),
        'ttl' => 3600, // 1 hour
    ],
    
    // Watch Mode Settings
    'watch' => [
        'port' => 8080,
        'host' => '127.0.0.1',
        'open_browser' => true,
    ],
];

// config/spectrum.php
'type_mappings' => [
    'json' => ['type' => 'object'],
    'uuid' => ['type' => 'string', 'format' => 'uuid'],
    'decimal' => ['type' => 'number', 'format' => 'float'],
],

// config/spectrum.php
'tags' => [
    // Group all authentication endpoints
    'api/v1/auth/*' => 'Authentication',
    
    // Specific endpoint mapping
    'api/v1/users/profile' => 'User Profile',
    
    // Multiple endpoints to same tag
    'api/v1/orders/*' => 'Orders',
    'api/v1/invoices/*' => 'Billing',
    'api/v1/payments/*' => 'Billing',
],

// Automatically generates examples from your Resources
class ProductResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->price,
            'currency' => 'USD',
            'in_stock' => $this->quantity > 0,
            'meta' => [
                'sku' => $this->sku,
                'weight' => $this->weight,
            ],
        ];
    }
}

// Automatic 422 validation error format
{
    "message": "The given data was invalid.",
    "errors": {
        "email": [
            "The email field is ction render($request, Throwable $exception)
    {
        if ($exception instanceof ModelNotFoundException) {
            return response()->json([
                'error' => 'Resource not found',
                'code' => 'RESOURCE_NOT_FOUND'
            ], 404);
        }
        
        return parent::render($request, $exception);
    }
}
bash
# Generate your API documentation instantly
php artisan spectrum:generate

# Watch mode for real-time updates
php artisan spectrum:watch
bash
# Generate OpenAPI documentation
php artisan spectrum:generate

# Generate in YAML format
php artisan spectrum:generate --format=yaml

# Custom output path
php artisan spectrum:generate --output=public/api-docs.json
bash
php artisan vendor:publish --tag=spectrum-config
bash
# Check registered routes
php artisan route:list --path=api

# Clear cache
php artisan spectrum:clear-cache
bash
# Ensure FormRequest is properly type-hinted
public function store(StoreUserRequest $request) // ✅ Correct
public function store(Request $request) // ❌ Won't detect custom rules