# 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**:
    

```bash
# 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
```

2. **Install AWS CLI**:
    
    Official Link: [Installing or updating to the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
    

```bash
# 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
```

3. **Install Serverless Framework**:
    

```bash
# 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](https://console.aws.amazon.com/console/home)
        
    * Sign up for a new account if you don't have one
        
    * AWS provides a free tier perfect for testing
        
2. **Create IAM User**:
    

```bash
# 1. Log into AWS Console
# 2. Go to IAM → Users → Add user
# 3. Username: laravel-lambda-deployer
# 4. Access type: Programmatic access
```

3. **Configure AWS Credentials**:
    

```bash
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**:
    

```bash
composer create-project laravel/laravel laravel-lambda
cd laravel-lambda
```

2. **Install Required Packages**:
    

```bash
composer require bref/bref bref/laravel-bridge
```

3. **Initialize Serverless Project**:
    

```bash
# 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:

```yaml
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**:
    

```bash
php artisan make:controller OrderController
```

2. **Add Controller Logic**:
    

```php
<?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);
    }
}
```

3. **Add Route** in `routes/api.php`:
    

```php
Route::post('/orders', [OrderController::class, 'create']);
```

## Deployment Process 🚀

1. **Prepare Environment**:
    

```bash
# Create production environment file
cp .env.example .env.production

# Generate application key
php artisan key:generate
```

2. **Store Sensitive Data** in AWS Systems Manager:
    

```bash
# 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.)
```

3. **Deploy**:
    

```bash
serverless deploy
```

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

## Testing Your Application 🧪

Test your deployed API using curl or Postman:

```bash
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**:
    

```php
// In AppServiceProvider.php boot method
public function boot()
{
    // Warm up commonly used services
    if (app()->environment('production')) {
        $this->warmUpCache();
    }
}
```

2. **Optimize Database Connections**:
    

```php
// config/database.php
'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST'),
    'strict' => false,
    'engine' => null,
    'modes' => [
        'ONLY_FULL_GROUP_BY',
    ],
    'sticky'    => true,
    'pool'      => 5,
]
```

3. **Configure Logging for CloudWatch**:
    

```php
// config/logging.php
'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['stderr'],
        'ignore_exceptions' => false,
    ],
]
```

## Monitoring & Troubleshooting 🔍

1. **View Logs**:
    

```bash
# View recent logs
serverless logs -f web

# Tail logs
serverless logs -f web -t
```

2. **Monitor Performance**:
    

* Use AWS CloudWatch dashboard
    
* Set up alarms for errors and latency
    
* Monitor cold start frequency
    

## Cost Management 💰

1. **Set Budget Alerts**:
    

```bash
aws budgets create-budget \
    --account-id your-account-id \
    --budget file://budget.json \
    --notifications-with-subscribers file://notifications.json
```

2. **Optimize Memory**:
    

```yaml
# In serverless.yml
provider:
    memorySize: 512 # Start with 512MB and adjust based on monitoring
```

## Common Issues & Solutions 🔧

1. **Deployment Timeout**:
    

```yaml
# In serverless.yml
provider:
    timeout: 30
```

2. **File Permissions**:
    

```bash
# Before deployment
chmod -R 755 storage bootstrap/cache
```

## Next Steps 🎯

1. **Add Authentication**:
    

```bash
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
```

2. **Implement Queue Workers**:
    

```yaml
# 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 📚

* [Official Bref Documentation](https://bref.sh/)
    
* [Laravel Documentation](https://laravel.com/docs)
    
* [AWS Lambda Best Practices](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)
    

Happy coding! 🚀
