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 apps on Laravel Vapor (AWS Lambda). Handles serverless bootstrapping and integrations with queues, databases, Redis, networking, CloudFront, and more for smooth, scalable deployments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laravel/vapor-core
    

    Ensure your Laravel app is compatible with the latest Vapor version (check Vapor docs).

  2. Check Vapor Environment: Use the helper to detect if the app is running on Vapor:

    if (app()->runningOnVapor()) {
        // Vapor-specific logic
    }
    
  3. First Use Case: Deploy a simple API endpoint to Vapor:

    vapor deploy production --yes
    

    Verify the endpoint works via AWS Lambda/CloudFront.

Where to Look First

  • Vapor Documentation for setup and configuration.
  • app()->runningOnVapor() helper to conditionally execute Vapor-specific logic.
  • vapor.yml for defining your Vapor infrastructure (queues, databases, etc.).
  • config/vapor.php for customizing Vapor behavior (e.g., environment variables, logging).

Implementation Patterns

Core Workflows

  1. Environment Detection: Use app()->runningOnVapor() to differentiate between local and Vapor environments:

    if (app()->runningOnVapor()) {
        // Enable Vapor-specific optimizations (e.g., SQS queues, RDS Proxy)
        Queue::laterOn('sqs-default');
    }
    
  2. Queue Management: Leverage Vapor’s SQS integration for background jobs:

    // Dispatch a job to the default SQS queue
    YourJob::dispatch();
    
    // Or specify a custom queue
    YourJob::dispatch()->onQueue('custom-sqs-queue');
    
  3. Database Connections: Use RDS Proxy for efficient database connections in serverless:

    // Configure RDS Proxy in vapor.yml
    databases:
        mysql:
            driver: mysql
            url: "mysql://user:pass@rds-proxy-endpoint:3306/db"
    
  4. API Gateway Integration: Access API Gateway request metadata (e.g., timestamps) via server variables:

    $timestamp = request()->server('aws.api_gateway.request_timestamp');
    
  5. Octane for Performance: Enable Octane in vapor.yml for reduced cold starts:

    octane:
        enabled: true
        driver: roadrunner
    
  6. Custom CLI Handlers: Register dynamic CLI handlers for Vapor-specific commands:

    Vapor::extend(function ($app) {
        $app->extend('cli.handler', function () {
            return new CustomVaporCliHandler();
        });
    });
    

Integration Tips

  • S3-Compatible Storage: Use vapor.yml to configure S3-compatible storage (e.g., MinIO):

    storage:
        s3:
            driver: s3
            url: "https://minio.example.com"
            endpoint: "minio.example.com"
    
  • Event-Driven Architecture: Subscribe to SQS events in vapor.yml:

    queues:
        my-queue:
            url: "arn:aws:sqs:us-east-1:123456789012:my-queue"
            events: ["s3:ObjectCreated:*"]
    
  • Logging: Expose AWS Lambda context for structured logging:

    \Log::info('Lambda execution context', [
        'request_id' => request()->server('aws.lambda.request_id'),
        'function_name' => request()->server('aws.lambda.function_name'),
    ]);
    
  • Environment Variables: Use VAPOR_ENV for non-standard environments:

    $env = env('VAPOR_ENV', env('APP_ENV'));
    

Gotchas and Tips

Pitfalls

  1. Cold Starts:

    • Issue: Lambda cold starts can delay initial requests.
    • Fix: Use Octane or provisioned concurrency in vapor.yml:
      octane:
          provisioned_concurrency: 5
      
  2. Database Timeouts:

    • Issue: MySQL "server gone away" errors due to wait_timeout.
    • Fix: Reset the session timeout in a database listener or middleware:
      DB::listen(function ($query) {
          if (app()->runningOnVapor()) {
              DB::statement("SET SESSION wait_timeout=28800");
          }
      });
      
  3. GET Requests with Bodies:

    • Issue: FPM may crash if a body is sent with a GET request.
    • Fix: Validate request methods or use middleware to strip bodies:
      if (request()->is('*') && request()->method() === 'GET' && request()->hasContent()) {
          abort(400, 'GET requests should not have a body.');
      }
      
  4. Multipart Form Data:

    • Issue: Parsing multidimensional arrays from multipart forms may fail.
    • Fix: Ensure php.ini has max_input_vars set sufficiently high or patch the parser.
  5. S3-Compatible Storage:

    • Issue: Some S3-compatible services (e.g., MinIO) may not work out-of-the-box.
    • Fix: Explicitly configure endpoints and credentials in vapor.yml.
  6. Scoped Bindings:

    • Issue: Scoped service container bindings may leak between requests.
    • Fix: Reset scoped instances before running Vapor jobs:
      app()->make(\Illuminate\Contracts\Console\Kernel::class)->handle(
          $input, $output
      );
      

Debugging Tips

  • Lambda Context: Access Lambda execution context via server variables:

    $context = [
        'request_id' => request()->server('aws.lambda.request_id'),
        'function_version' => request()->server('aws.lambda.function_version'),
    ];
    
  • Health Checks: Use Vapor’s health checker endpoint (/health) to monitor Lambda functions:

    curl https://your-app.vapor.build/health
    
  • Logging: Enable structured logging with Lambda context:

    \Log::withContext([
        'lambda' => request()->server('aws.lambda', []),
    ])->info('Event processed');
    

Extension Points

  1. Custom Lambda Events: Extend SQS event handling for custom Lambda triggers:

    Vapor::extend(function ($app) {
        $app->extend('queue.worker', function ($worker) {
            $worker->on('custom-event', function ($event) {
                // Handle custom SQS event
            });
        });
    });
    
  2. Dynamic CLI Handlers: Register custom CLI handlers for Vapor:

    Vapor::extend(function ($app) {
        $app->extend('cli.handler', function () {
            return new class implements \Symfony\Component\Console\CommandLoader\CommandLoaderInterface {
                public function getCommands() {
                    return ['vapor:custom-command' => new CustomCommand()];
                }
            };
        });
    });
    
  3. Override Vapor Keys: Abstract or override Vapor’s configuration keys:

    config(['vapor.key' => 'custom-key']);
    
  4. Custom Storage Adapters: Extend S3-compatible storage support:

    Storage::extend('minio', function ($app, $config) {
        return new MinioAdapter($config);
    });
    

Configuration Quirks

  • Environment Variables: Ensure VAPOR_ENV is set correctly for non-standard environments:

    export VAPOR_ENV=staging
    
  • vapor.yml Validation: Validate vapor.yml syntax before deploying:

    vapor validate
    
  • Octane Cookies: Fix Octane cookie issues by ensuring proper session configuration:

    config(['session.driver' => 'redis']);
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport