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:
- 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
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
- 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:
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
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
- 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!
- Create New Laravel Project:
composer create-project laravel/laravel laravel-lambda
cd laravel-lambda
- Install Required Packages:
composer require bref/bref bref/laravel-bridge
- 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 π
- Create Order Controller:
php artisan make:controller OrderController
- 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);
}
}
- Add Route in
routes/api.php:
Route::post('/orders', [OrderController::class, 'create']);
Deployment Process π
- Prepare Environment:
# Create production environment file
cp .env.example .env.production
# Generate application key
php artisan key:generate
- 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.)
- 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 π‘
- Handle Cold Starts:
// In AppServiceProvider.php boot method
public function boot()
{
// Warm up commonly used services
if (app()->environment('production')) {
$this->warmUpCache();
}
}
- 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,
]
- Configure Logging for CloudWatch:
// config/logging.php
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['stderr'],
'ignore_exceptions' => false,
],
]
Monitoring & Troubleshooting π
- View Logs:
# View recent logs
serverless logs -f web
# Tail logs
serverless logs -f web -t
- Monitor Performance:
Use AWS CloudWatch dashboard
Set up alarms for errors and latency
Monitor cold start frequency
Cost Management π°
- Set Budget Alerts:
aws budgets create-budget \
--account-id your-account-id \
--budget file://budget.json \
--notifications-with-subscribers file://notifications.json
- Optimize Memory:
# In serverless.yml
provider:
memorySize: 512 # Start with 512MB and adjust based on monitoring
Common Issues & Solutions π§
- Deployment Timeout:
# In serverless.yml
provider:
timeout: 30
- File Permissions:
# Before deployment
chmod -R 755 storage bootstrap/cache
Next Steps π―
- Add Authentication:
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
- 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! π




