Skip to main content

Command Palette

Search for a command to run...

The Complete Guide to Running Laravel on AWS Lambda: From Zero to Hero πŸš€

Updated
β€’5 min read
The Complete Guide to Running Laravel on AWS Lambda: From Zero to Hero πŸš€

Laravel on AWS Lambda

Imagine running a restaurant where you only pay for the kitchen when someone orders food - that's exactly how AWS Lambda works! In this comprehensive guide, we'll walk through deploying a Laravel application on AWS Lambda, making it as simple as cooking your favorite meal.

What We'll Build 🎯

We'll create a food ordering system that:

  • Scales automatically with demand

  • Only charges when in use

  • Requires zero server maintenance

  • Handles traffic spikes effortlessly

Complete Prerequisites Checklist πŸ› οΈ

Let's gather all our ingredients before we start cooking:

  1. Local Development Tools:
# Check if you have PHP 8.1+
php -v

# Check if you have Node.js (14.x or higher)
node --v

# Check if you have Composer
composer --version
  1. Install AWS CLI:

    Official Link: Installing or updating to the latest version of the AWS CLI

# For Windows: Download from AWS website
# https://awscli.amazonaws.com/AWSCLIV2.msi
# For Mac:
brew install awscli

# For Linux:
sudo apt-get update
sudo apt-get install awscli

# Verify installation
aws --version
  1. Install Serverless Framework:
# Install globally
npm install -g serverless

# Verify installation
serverless --version
# or
sls --version

Setting Up AWS Credentials πŸ”‘

Before we start coding, let's set up our AWS access:

  1. Create AWS Account:

    • Go to AWS Console

    • Sign up for a new account if you don't have one

    • AWS provides a free tier perfect for testing

  2. Create IAM User:

# 1. Log into AWS Console
# 2. Go to IAM β†’ Users β†’ Add user
# 3. Username: laravel-lambda-deployer
# 4. Access type: Programmatic access
  1. Configure AWS Credentials:
aws configure

# You'll be prompted for:
AWS Access Key ID: [Your Access Key]
AWS Secret Access Key: [Your Secret Key]
Default region name: us-east-1 # Region closest to your customer
Default output format: json

Creating Your Laravel Project πŸ“¦

Now let's start building!

  1. Create New Laravel Project:
composer create-project laravel/laravel laravel-lambda
cd laravel-lambda
  1. Install Required Packages:
composer require bref/bref bref/laravel-bridge
  1. Initialize Serverless Project:
# Initialize a new serverless project
serverless create --template aws-nodejs

# This creates serverless.yml - we'll replace its contents

Configure Serverless Deployment πŸ”§

Create/Update serverless.yml in your project root:

service: laravel-food-delivery

provider:
    name: aws
    region: us-east-1
    runtime: provided.al2
    environment:
        APP_ENV: production
        APP_KEY: ${ssm:/laravel-lambda/app-key}
        DB_CONNECTION: mysql
        DB_HOST: ${ssm:/laravel-lambda/db-host}
        DB_DATABASE: ${ssm:/laravel-lambda/db-name}
        DB_USERNAME: ${ssm:/laravel-lambda/db-user}
        DB_PASSWORD: ${ssm:/laravel-lambda/db-pass}

plugins:
    - ./vendor/bref/bref

functions:
    web:
        handler: public/index.php
        description: 'Laravel application'
        runtime: php-81-fpm
        timeout: 28
        layers:
            - ${bref:layer.php-81-fpm}
        events:
            - httpApi: '*'

    artisan:
        handler: artisan
        description: 'Laravel Artisan'
        runtime: php-81-cli
        timeout: 120
        layers:
            - ${bref:layer.php-81-cli}

package:
    exclude:
        - node_modules/**
        - tests/**
        - storage/logs/**

Creating Our Food Ordering System πŸ•

  1. Create Order Controller:
php artisan make:controller OrderController
  1. Add Controller Logic:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class OrderController extends Controller
{
    public function create(Request $request)
    {
        // Validate order
        $validated = $request->validate([
            'items' => 'required|array',
            'items.*.name' => 'required|string',
            'items.*.quantity' => 'required|integer|min:1',
            'delivery_address' => 'required|string',
            'contact_number' => 'required|string'
        ]);

        // Generate order number
        $orderNumber = 'ORD-' . strtoupper(uniqid());

        // Calculate estimated delivery time
        $estimatedDelivery = now()->addMinutes(45);

        // Process order (in real app, save to database)
        $order = [
            'order_number' => $orderNumber,
            'items' => $validated['items'],
            'delivery_address' => $validated['delivery_address'],
            'contact_number' => $validated['contact_number'],
            'status' => 'received',
            'estimated_delivery' => $estimatedDelivery->format('Y-m-d H:i:s')
        ];

        // Log order (CloudWatch will capture this)
        Log::info('New order received', $order);

        return response()->json([
            'message' => 'Order received successfully!',
            'order' => $order
        ], 201);
    }
}
  1. Add Route in routes/api.php:
Route::post('/orders', [OrderController::class, 'create']);

Deployment Process πŸš€

  1. Prepare Environment:
# Create production environment file
cp .env.example .env.production

# Generate application key
php artisan key:generate
  1. Store Sensitive Data in AWS Systems Manager:
# Store app key
aws ssm put-parameter \
    --name "/laravel-lambda/app-key" \
    --type "SecureString" \
    --value "base64:your-key-here"

# Repeat for other sensitive values (DB credentials etc.)
  1. Deploy:
serverless deploy

The deployment process will output your Lambda URL. Save this!

Testing Your Application πŸ§ͺ

Test your deployed API using curl or Postman:

curl -X POST https://your-lambda-url/api/orders \
-H "Content-Type: application/json" \
-d '{
    "items": [
        {
            "name": "Margherita Pizza",
            "quantity": 2
        },
        {
            "name": "Coca Cola",
            "quantity": 3
        }
    ],
    "delivery_address": "123 Main St, Apt 4B",
    "contact_number": "+1-234-567-8900"
}'

Best Practices & Optimization πŸ’‘

  1. Handle Cold Starts:
// In AppServiceProvider.php boot method
public function boot()
{
    // Warm up commonly used services
    if (app()->environment('production')) {
        $this->warmUpCache();
    }
}
  1. Optimize Database Connections:
// config/database.php
'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST'),
    'strict' => false,
    'engine' => null,
    'modes' => [
        'ONLY_FULL_GROUP_BY',
    ],
    'sticky'    => true,
    'pool'      => 5,
]
  1. Configure Logging for CloudWatch:
// config/logging.php
'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['stderr'],
        'ignore_exceptions' => false,
    ],
]

Monitoring & Troubleshooting πŸ”

  1. View Logs:
# View recent logs
serverless logs -f web

# Tail logs
serverless logs -f web -t
  1. Monitor Performance:
  • Use AWS CloudWatch dashboard

  • Set up alarms for errors and latency

  • Monitor cold start frequency

Cost Management πŸ’°

  1. Set Budget Alerts:
aws budgets create-budget \
    --account-id your-account-id \
    --budget file://budget.json \
    --notifications-with-subscribers file://notifications.json
  1. Optimize Memory:
# In serverless.yml
provider:
    memorySize: 512 # Start with 512MB and adjust based on monitoring

Common Issues & Solutions πŸ”§

  1. Deployment Timeout:
# In serverless.yml
provider:
    timeout: 30
  1. File Permissions:
# Before deployment
chmod -R 755 storage bootstrap/cache

Next Steps 🎯

  1. Add Authentication:
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  1. Implement Queue Workers:
# In serverless.yml
functions:
    queue:
        handler: artisan
        timeout: 120
        layers:
            - ${bref:layer.php-81-cli}
        events:
            - schedule: rate(1 minute)

Conclusion πŸŽ‰

You now have a fully functional Laravel application running on AWS Lambda! This serverless setup provides:

  • Automatic scaling

  • Pay-per-use pricing

  • Zero server maintenance

  • Enterprise-grade reliability

Remember, like learning to cook, mastering serverless takes practice. Start small, monitor your application, and scale as needed.

Additional Resources πŸ“š

Happy coding! πŸš€

More from this blog

Sohag's Notes

79 posts

Tech Lead at MobyPay | Certified Laravel Developer | PHP JS GO | DevOps Enthusiast | Open to projects