The Complete Guide to Running Laravel on AWS Lambda: From Zero to Hero ๐

WhoAmI => notes.sohag.pro/author
Search for a command to run...

WhoAmI => notes.sohag.pro/author
No comments yet. Be the first to comment.
GitHub Actions and CI/CD Imagine you're preparing a fancy dinner party. There's chopping, cooking, plating, and cleaning involved. Now, wouldn't it be amazing if you had a magical kitchen assistant who could automatically taste-test your food, ensure...
I had a solid list of reasons my life wasn't moving faster, until a grainy old lecture pointed out the one name missing from it

The finale isn't a victory lap. It's the story of the control I shipped that did nothing, the footgun still sitting in my demo, and the handful of things I'd keep exactly as they are.

How do you hold a large payment for a second pair of eyes without ever letting the unapproved money touch a balance, and how do you stream that decision to the outside world without standing up a broker?

How do you show the total under a parent account when the whole system refuses to store a balance? A recursive query, a trigger that refuses to draw a circle, and a rule about what actually has to sum to zero.

Every time I wanted to change an FX rate I had to edit a file on the server and restart the app. So I moved rates and markup into a live admin API, and then audited it hard enough to find the bug that quietly undid the whole thing.

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.
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
Let's gather all our ingredients before we start cooking:
# 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 globally
npm install -g serverless
# Verify installation
serverless --version
# or
sls --version
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
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
Now let's start building!
composer create-project laravel/laravel laravel-lambda
cd laravel-lambda
composer require bref/bref bref/laravel-bridge
# Initialize a new serverless project
serverless create --template aws-nodejs
# This creates serverless.yml - we'll replace its contents
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/**
php artisan make:controller OrderController
<?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);
}
}
routes/api.php:Route::post('/orders', [OrderController::class, 'create']);
# Create production environment file
cp .env.example .env.production
# Generate application key
php artisan key:generate
# 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.)
serverless deploy
The deployment process will output your Lambda URL. Save this!
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"
}'
// In AppServiceProvider.php boot method
public function boot()
{
// Warm up commonly used services
if (app()->environment('production')) {
$this->warmUpCache();
}
}
// config/database.php
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST'),
'strict' => false,
'engine' => null,
'modes' => [
'ONLY_FULL_GROUP_BY',
],
'sticky' => true,
'pool' => 5,
]
// config/logging.php
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['stderr'],
'ignore_exceptions' => false,
],
]
# View recent logs
serverless logs -f web
# Tail logs
serverless logs -f web -t
Use AWS CloudWatch dashboard
Set up alarms for errors and latency
Monitor cold start frequency
aws budgets create-budget \
--account-id your-account-id \
--budget file://budget.json \
--notifications-with-subscribers file://notifications.json
# In serverless.yml
provider:
memorySize: 512 # Start with 512MB and adjust based on monitoring
# In serverless.yml
provider:
timeout: 30
# Before deployment
chmod -R 755 storage bootstrap/cache
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
# In serverless.yml
functions:
queue:
handler: artisan
timeout: 120
layers:
- ${bref:layer.php-81-cli}
events:
- schedule: rate(1 minute)
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.
Happy coding! ๐