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

Vapor Core Laravel Package

laravel/vapor-core

Core runtime and service providers for running Laravel on Vapor (AWS Lambda). Handles serverless bootstrapping and integrations like queues, databases, Redis, networking, and CDN, helping Laravel apps scale smoothly in a serverless environment.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   Add `laravel/vapor-core` to your `composer.json`:
   ```bash
   composer require laravel/vapor-core

Ensure your config/app.php includes the VaporServiceProvider under providers:

Laravel\Vapor\Core\VaporServiceProvider::class,
  1. First Use Case: Check if your app is running on Vapor in any controller/middleware:

    use Laravel\Vapor\Core\Facades\Vapor;
    
    if (Vapor::running()) {
        // Vapor-specific logic (e.g., optimize for cold starts)
        \Log::info('Running on Vapor!');
    }
    
  2. Key Entry Points:

    • Runtime Detection: Use Vapor::running() to conditionally execute Vapor-specific logic.
    • Environment Variables: Access Vapor-provided env vars via config('vapor.*') or env('VAPOR_*').
    • AWS Context: Leverage Vapor::executionContext() to log Lambda metadata (e.g., awsRequestId).
  3. Where to Look First:

    • Vapor Docs for deployment patterns.
    • vendor/laravel/vapor-core/src/Facades/Vapor.php for API reference.
    • config/vapor.php (auto-generated) for Vapor-specific configurations.

Implementation Patterns

Core Workflows

1. Runtime Adaptations

  • Cold Start Optimization: Lazy-load heavy dependencies (e.g., Eloquent models, third-party SDKs) after the request starts:
    if (!Vapor::running()) {
        $this->loadHeavyDependencies();
    }
    
  • Connection Handling: Reset database connections between Lambda invocations to avoid stale connections:
    if (Vapor::running()) {
        DB::disconnect();
        DB::reconnect();
    }
    

2. Event-Driven Integrations

  • SQS Queue Listeners: Use Vapor::isSqsEvent() to handle SQS-triggered Lambda invocations:
    if (Vapor::isSqsEvent()) {
        $event = Vapor::event();
        // Process SQS message
    }
    
  • API Gateway Events: Access raw API Gateway payloads via Vapor::event() for custom routing:
    $request = Vapor::event()->get('body');
    

3. Environment Awareness

  • Dynamic Configuration: Override settings based on the runtime:
    $config = Vapor::running()
        ? config('vapor.optimized_settings')
        : config('local.settings');
    
  • Environment Variables: Use env('VAPOR_REGION') or config('vapor.region') to fetch Vapor-specific AWS regions.

4. Logging and Observability

  • Lambda Context Logging: Attach AWS Lambda metadata to logs:
    \Log::info('Processing request', [
        'awsRequestId' => Vapor::executionContext()['awsRequestId'],
        'functionName' => Vapor::executionContext()['functionName'],
    ]);
    
  • Structured Logging: Use Vapor::log() for structured JSON logs compatible with AWS CloudWatch:
    Vapor::log('user.created', ['user_id' => 123]);
    

5. Octane Integration

  • Real-Time HTTP Server: Ensure Octane is configured for Vapor by extending VaporOctaneHandler:
    use Laravel\Vapor\Core\Octane\VaporOctaneHandler;
    
    return new class extends VaporOctaneHandler {
        protected function configure(): void {
            $this->withFileStorage();
        }
    };
    

6. Background Jobs

  • Queue Workers: Use Vapor::queue() to interact with SQS queues directly:
    Vapor::queue('orders')->push(new ProcessOrder($orderId));
    
  • Job Retries: Configure max retries for Vapor queues in config/vapor.php:
    'queues' => [
        'orders' => [
            'maxRetries' => 3,
            'visibilityTimeout' => 30,
        ],
    ],
    

7. Storage and Filesystems

  • S3-Compatible Storage: Configure custom S3 endpoints (e.g., MinIO) in config/filesystems.php:
    'disks' => [
        's3' => [
            'driver' => 's3',
            'url' => env('S3_ENDPOINT', 'https://s3.amazonaws.com'),
            // ... other config
        ],
    ],
    

Integration Tips

Laravel Components

  • Routing: Use Route::vapor() to define Vapor-specific routes (e.g., API Gateway integrations):
    Route::vapor('GET', '/webhook', [WebhookController::class, 'handle']);
    
  • Middleware: Skip middleware on Vapor for performance:
    public function handle($request, Closure $next) {
        if (Vapor::running() && !$request->hasHeader('x-custom-header')) {
            abort(403);
        }
        return $next($request);
    }
    
  • Artisan Commands: Register Vapor-specific commands in AppServiceProvider:
    if (Vapor::running()) {
        $this->commands([
            \App\Console\Commands\Vapor\OptimizeCommand::class,
        ]);
    }
    

AWS Services

  • RDS/ElastiCache: Use config('database.connections.mysql.host') to dynamically resolve Vapor-provided endpoints.
  • CloudFront: Cache headers are automatically optimized for Vapor. Use Cache::tags() for invalidation:
    Cache::tags(['vapor-cdn'])->put('key', 'value', now()->addHours(1));
    

Testing

  • Local Vapor Simulation: Use the vapor:test Artisan command to simulate Lambda invocations:
    php artisan vapor:test --event=api-gateway
    
  • Mocking: Stub Vapor::running() in tests:
    Vapor::shouldReceive('running')->andReturn(true);
    

Gotchas and Tips

Pitfalls

  1. Cold Start Latency:

    • Issue: Heavy dependencies (e.g., php-redis, pdo_mysql) increase cold start times.
    • Fix: Lazy-load them or use Vapor’s provisioned concurrency.
    • Tip: Profile cold starts with Vapor::logColdStart():
      if (Vapor::running()) {
          Vapor::logColdStart();
      }
      
  2. Connection Leaks:

    • Issue: Stale database/Redis connections between invocations.
    • Fix: Reset connections explicitly:
      if (Vapor::running()) {
          DB::disconnect();
          Redis::connection()->disconnect();
      }
      
    • Tip: Use DB::retryUsing() for transient failures:
      DB::retryUsing(function () {
          return DB::connection()->getPdo();
      });
      
  3. Timeout Handling:

    • Issue: Lambda’s 15-minute max timeout may cut off long-running jobs.
    • Fix: Break jobs into smaller chunks or use Step Functions.
    • Tip: Log remaining time with:
      \Log::info('Remaining time:', [
          'seconds' => Vapor::executionContext()['remainingTime'] ?? 0,
      ]);
      
  4. Environment Variable Conflicts:

    • Issue: Local .env vars may override Vapor’s VAPOR_* vars.
    • Fix: Use config('vapor.*') instead of env() where possible.
    • Tip: Prefer VAPOR_ENV over APP_ENV for Vapor-specific logic.
  5. Multipart Form Data:

    • Issue: Parsing nested arrays from multipart requests may fail.
    • Fix: Use Vapor::parseMultipart():
      $data = Vapor::parseMultipart($request->input());
      
  6. Octane + Vapor:

    • Issue: Octane’s event loop may conflict with Lambda’s async runtime.
    • Fix: Use VaporOctaneHandler and avoid blocking calls in Octane workers.
    • Tip: Disable Octane for CLI jobs:
      if (Vapor::running() && $this->isCli()) {
          $this->disableOctane();
      }
      
  7. SQS Visibility Timeouts:

    • Issue: Long-running jobs may exceed SQS visibility timeouts.
    • **
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony