Serverless AI Image Generation with Laravel 11, Stable Diffusion API, Cloudflare Workers

Mahmut Sarıkaya 4 min read 45 Views 0
Serverless AI Image Generation with Laravel 11, Stable Diffusion API, Cloudflare Workers

Why serverless AI image generation matters

Imagine a marketing team that needs a fresh visual for every new campaign, but the budget for a graphics designer is limited. In 2023, over 60% of startups reported using AI tools to create on‑demand images, yet many still host these models on expensive virtual machines. A serverless architecture eliminates idle compute costs while delivering the same creative power at scale.

System requirements and prerequisites

Before writing code, confirm that you have PHP 8.2+, Composer 2.5+, and a Cloudflare account with Workers enabled. The Stable Diffusion API you’ll call is a hosted service, so no GPU is required locally. Allocate a MySQL 5.7+ database for Laravel, and set up a free Cloudflare Workers KV namespace for caching generated URLs.

Setting up a fresh Laravel 11 project

Start by creating the skeleton with Composer, then configure environment variables for the API key and the Worker endpoint. The following commands bootstrap the application:

composer create-project laravel/laravel ai‑image‑service "11.*" && cd ai‑image‑service
cp .env.example .env
composer require guzzlehttp/guzzle

In .env add:

STABLE_DIFFUSION_API_KEY=your_api_key_here
WORKER_ENDPOINT=https://your‑worker.subdomain.workers.dev

These variables keep secrets out of source control and allow you to swap endpoints without code changes.

Integrating the Stable Diffusion API

The API expects a JSON payload with a prompt and optional parameters like width, height, and steps. Create a service class that wraps Guzzle calls and handles error codes gracefully.

namespace App\Services;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class StableDiffusionService
{
protected $client;

public function __construct()
{
$this->client = new Client([
'base_uri' => 'https://api.stablediffusionapi.com/v1/',
'timeout' => 30,
]);
}

public function generate(string $prompt, array $options = []): string
{
$payload = array_merge(['prompt' => $prompt], $options);
try {
$response = $this->client->post('text2img', [
'headers' => [
'Authorization' => 'Bearer ' . env('STABLE_DIFFUSION_API_KEY'),
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
$data = json_decode($response->getBody(), true);
return $data['output'][0] ?? '';
} catch (GuzzleException $e) {
// Log and rethrow a generic exception for the controller
logger()->error('Stable Diffusion error: ' . $e->getMessage());
throw new \RuntimeException('Image generation failed');
}
}
}

The service returns a direct URL to the generated PNG, which you will forward to the client through a Cloudflare Worker.

Deploying a Cloudflare Worker as a proxy

Workers act as edge functions that can cache responses for up to 24 hours, drastically reducing latency for repeat requests. The script below validates the incoming request, forwards it to the Stable Diffusion endpoint, stores the result in KV, and returns a short‑lived signed URL.

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
if (request.method !== 'POST') {
return new Response('Method Not Allowed', {status: 405})
}
const body = await request.json()
const apiKey = STABLE_DIFFUSION_API_KEY // set in Worker secret
const resp = await fetch('https://api.stablediffusionapi.com/v1/text2img', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
})
const result = await resp.json()
const imageUrl = result.output[0]r> // Cache the URL for 12 hours
await IMAGE_CACHE.put(imageUrl, JSON.stringify(result), {expirationTtl: 43200})
return new Response(JSON.stringify({url: imageUrl}), {
headers: {'Content-Type': 'application/json'}
})
}

Deploy with wrangler publish after configuring wrangler.toml with your KV namespace and secret.

Connecting Laravel to the Worker

In Laravel, create a controller that forwards the user prompt to the Worker endpoint instead of calling the API directly. This keeps your API key out of the application logs and leverages edge caching.

namespace App\Http\Controllers;

use App\Services\StableDiffusionService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ImageController extends Controller
{
public function generate(Request $request)
{
$request->validate(['prompt' => 'required|string|max:200']);
$payload = [
'prompt' => $request->input('prompt'),
'width' => 512,
'height' => 512,
'steps' => 30,
];

$workerResponse = Http::withHeaders([
'Content-Type' => 'application/json',
])->post(env('WORKER_ENDPOINT'), $payload);

if ($workerResponse->failed()) {
return response()->json(['error' => 'Generation failed'], 502);
}
return response()->json(['image_url' => $workerResponse->json('url')]);
}
}

Register the route in routes/web.php:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;

Route::post('api/generate-image', [ImageController::class, 'generate']);

Now a single POST request from any front‑end (React, Vue, or plain HTML) triggers the full serverless pipeline.

Testing, monitoring, and scaling considerations

Run a quick sanity test with curl:

curl -X POST https://your‑app.test/api/generate-image \
-H "Content-Type: application/json" \
-d '{"prompt":"A futuristic city skyline at sunset"}'

The response should contain an image_url. Use Laravel Telescope or the built‑in logs to trace any failures. Because the heavy lifting occurs in the Worker, your Laravel instance can be scaled down to a single dyno or even a free tier on platforms like Render or Fly.io, preserving the serverless promise.

Conclusion

By combining Laravel 11’s expressive routing, the Stable Diffusion API’s high‑quality output, and Cloudflare Workers’ edge caching, you achieve a truly serverless AI image generation service. The architecture minimizes operational overhead, keeps costs predictable, and delivers millisecond‑level responses to end users. Start with the steps above, iterate on prompt handling, and watch your product’s visual content pipeline become fully automated.

Sources

Laravel Official Documentation, Cloudflare Workers Documentation, Stable Diffusion API Reference

Author: Mahmut Sarıkaya — sarikayadev.com

Tags: #laravel 11 #stable diffusion api #ai image generation #cloudflare workers #serverless architecture
Share:
M

Written by

Mahmut Sarıkaya

Software Developer

Comments

No comments yet. Be the first to share your thoughts!

Leave a Comment

8 + 2 =