← Blog

Claude API Laravel PHP Integration Guide

2026-11-10 · 5 min read · SubToAPI Team

Integrating Claude into a Laravel application means wiring up Anthropic's HTTP API (or a compatible endpoint) through Laravel's native Http facade, wrapping it in a service class, and handling streaming responses properly since Laravel's default synchronous request lifecycle doesn't stream by default. This guide walks through a working setup you can drop into a Laravel 10/11 project today.

If you've searched for a Claude API Laravel PHP integration guide, you're likely trying to decide between calling Anthropic's API directly from PHP or going through a gateway that gives you an OpenAI-style key and dashboard. Both approaches use the same Laravel code underneath — only the base URL and headers change. We'll show the direct approach first, then how it simplifies with a gateway like SubToAPI.

Setting Up Your Laravel Project

Start with a standard Laravel install and add your credentials to .env:

ANTHROPIC_API_KEY=sk-ant-xxxxx
ANTHROPIC_MODEL=claude-sonnet-4-20250514

Register the config in config/services.php:

'anthropic' => [
    'key' => env('ANTHROPIC_API_KEY'),
    'model' => env('ANTHROPIC_MODEL', 'claude-sonnet-4-20250514'),
    'base_url' => env('ANTHROPIC_BASE_URL', 'https://api.anthropic.com/v1'),
],

Keeping the base URL configurable matters — it lets you swap providers or gateways without touching application code, which is useful if you later route traffic through SubToAPI or run staging against a mock endpoint.

Building a Claude Service Class

Create app/Services/ClaudeClient.php:

namespace App\Services;

use Illuminate\Support\Facades\Http;

class ClaudeClient
{
    public function message(array $messages, string $system = null, int $maxTokens = 1024): array
    {
        $payload = [
            'model' => config('services.anthropic.model'),
            'max_tokens' => $maxTokens,
            'messages' => $messages,
        ];

        if ($system) {
            $payload['system'] = $system;
        }

        $response = Http::withHeaders([
            'x-api-key' => config('services.anthropic.key'),
            'anthropic-version' => '2023-06-01',
            'content-type' => 'application/json',
        ])
        ->baseUrl(config('services.anthropic.base_url'))
        ->post('/messages', $payload);

        $response->throw();

        return $response->json();
    }
}

Bind it in a service provider or just resolve it via Laravel's container:

$claude = app(\App\Services\ClaudeClient::class);

$result = $claude->message([
    ['role' => 'user', 'content' => 'Summarize the attached changelog in three bullets.'],
]);

echo $result['content'][0]['text'];

This is enough for a basic controller action, an Artisan command, or a queued job that calls Claude and stores the result.

Handling Streaming Responses

Streaming in Laravel requires bypassing the normal buffered response and using a StreamedResponse with Server-Sent Events. Here's a minimal controller:

use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\Support\Facades\Http;

public function stream()
{
    return new StreamedResponse(function () {
        $response = Http::withHeaders([
            'x-api-key' => config('services.anthropic.key'),
            'anthropic-version' => '2023-06-01',
        ])->withOptions([
            'stream' => true,
        ])->post(config('services.anthropic.base_url') . '/messages', [
            'model' => config('services.anthropic.model'),
            'max_tokens' => 1024,
            'stream' => true,
            'messages' => [
                ['role' => 'user', 'content' => 'Write a short poem about deployment pipelines.'],
            ],
        ]);

        $body = $response->toPsrResponse()->getBody();

        while (!$body->eof()) {
            echo $body->read(1024);
            flush();
        }
    }, 200, [
        'Content-Type' => 'text/event-stream',
        'Cache-Control' => 'no-cache',
        'X-Accel-Buffering' => 'no',
    ]);
}

Guzzle's streaming support via Laravel's HTTP client works, but it requires disabling output buffering on your web server (PHP-FPM + Nginx usually needs X-Accel-Buffering: no, and ob_end_flush() if any buffering middleware is active). If you're running behind Octane or a queue worker instead of a traditional request/response cycle, this gets more involved — which is one reason teams offload streaming to a gateway that already handles SSE correctly and exposes it the same way regardless of your PHP runtime. SubToAPI's streaming docs cover the exact event format if you go that route.

Error Handling and Retries

Claude's API returns standard HTTP status codes: 429 for rate limits, 529 for overload, 401 for bad credentials. A production-ready Laravel integration should retry transient errors with backoff:

$response = Http::retry(3, 200, function ($exception) {
    return $exception->response?->status() === 429
        || $exception->response?->status() === 529;
})
->withHeaders([...])
->post('/messages', $payload);

Wrap the whole call in a try/catch and log the request_id header from failed responses — Anthropic support asks for it when debugging issues, and it's worth storing alongside your application logs.

Using Laravel Jobs for Long Requests

For anything beyond a quick chat reply — document analysis, multi-turn agent loops, tool-use chains — dispatch the Claude call as a queued job rather than blocking the HTTP request:

class GenerateSummaryJob implements ShouldQueue
{
    public function handle(ClaudeClient $claude)
    {
        $result = $claude->message([...]);
        // persist result, broadcast event, notify user
    }
}

This avoids PHP-FPM worker exhaustion and lets you set sane job timeouts independent of your web server's timeout config.

Simplifying with SubToAPI

If you're already paying for Claude access and want an HTTPS API with a clean key, team seats, and usage visibility without managing Anthropic credentials directly in every environment, SubToAPI sits as a drop-in replacement for the base URL above. The Laravel code is identical — swap ANTHROPIC_BASE_URL for https://api.subtoapi.app/v1 and use a sub_live_... key instead of your Anthropic key:

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "content-type: application/json" \
  -d '{"model":"claude-sonnet-4-20250514","max_tokens":1024,"messages":[{"role":"user","content":"Hello"}]}'

That's useful for Laravel teams where multiple engineers or environments need isolated keys without sharing one raw Anthropic credential. Check /docs/quickstart and /docs/messages for the full request/response shape, and /pricing for plan details — Solo starts at €9/month with a free trial at /signup.

Tool Use from Laravel

If your Laravel app needs Claude to call functions — looking up orders, querying a database, hitting internal APIs — the request structure uses the same /messages endpoint with a tools array and a loop that feeds tool_result blocks back in. See /docs/tools for the schema; the Laravel-side pattern is just a while loop around your ClaudeClient::message() call that checks for stop_reason === 'tool_use'.

Questions

Does Laravel need a special SDK for the Claude API? No. Laravel's built-in Http facade (Guzzle under the hood) handles standard requests fine. You only need extra configuration for streaming responses, since those require disabling output buffering.

Can I call Claude from Laravel queue workers? Yes, and it's recommended for anything longer than a single quick response. Dispatch a job, call Claude inside handle(), and store or broadcast the result — this avoids tying up web server workers on slow requests.

What's the difference between calling Anthropic directly and using SubToAPI from Laravel? The Laravel code is nearly identical — only the base URL and auth header change. SubToAPI adds application-level API keys, per-seat team access, and usage metadata without changing your integration logic.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →