Adding a Claude-powered feature to a Laravel app, properly · Part 1 of 6
The SDK, one client in the container, and the first call
Install the official PHP SDK, bind one client from config, send the first message and put a price on it, and test all of it without the network.
By Abhishek Fouzdar
This part ends with the official Anthropic PHP SDK installed in InvoiceMini, one client in the service container, a command that sends a message and prints what it cost, and tests that exercise all of it without touching the network. The series introduction explains what InvoiceMini is and what the six parts build.
The SDK, not a wrapper
The first decision is the one most Laravel tutorials get wrong: how the app talks to the API. The options are a community package, Laravel's HTTP client against the REST endpoint, or the official SDK.
The official SDK won. anthropic-ai/sdk 1.4.0 came out on 2 November 2026, it speaks the current API version (2026-10-21), it has typed responses, streaming, structured outputs and a tool runner, and when the API changes the SDK changes with it. A wrapper package adds a second thing that can lag. Raw HTTP means writing the request shapes yourself, and the shapes have moved several times this year: thinking configuration, the output format parameter, the auth header. Every one of those moves is a bug you would ship.
composer require "anthropic-ai/sdk:^1.4"
The SDK needs a PSR-18 HTTP client and a PSR-17 factory; it finds Guzzle, which Laravel already ships. That detail matters later, because a PSR-18 client is also how tests fake the API.
Configuration
config/claude.php holds everything the app knows about the API. The key is the only thing that comes from the environment. The models and their prices are decisions, so they live in version control where a pull request can change them.
<?php
// Everything the app knows about the Claude API lives here. The key comes from the
// environment; the models and their prices are decisions, so they are in version control.
return [
'api_key' => env('ANTHROPIC_API_KEY'),
'models' => [
// Reasoning, drafting, the assistant: the current Opus.
'default' => 'claude-opus-5-5',
// Classification and other short, high-volume calls: the current Haiku.
'fast' => 'claude-haiku-5-5',
],
// USD per million tokens, from https://claude.com/pricing#api on 3 November 2026.
// Used to put a price on every call the app makes; see app/AI/Cost.php.
'prices' => [
'claude-opus-5-5' => ['input' => 4.00, 'output' => 20.00],
'claude-haiku-5-5' => ['input' => 0.10, 'output' => 0.50],
],
// Seconds before a request is abandoned, and how many times the SDK retries a 429,
// a 5xx or a dropped connection before giving up. Streaming requests ignore the timeout.
'timeout' => 60,
'max_retries' => 2,
];
Two models, on purpose. Opus 5.5 does the work that needs judgement: drafting, the assistant in part 4, the monthly summary in part 5. Haiku 5.5 is forty times cheaper on input and does the short, high-volume calls where a smaller model is plenty, like classifying a client's reply in part 5. Naming them default and fast in config means the rest of the app never mentions a model id, and swapping a model is a one-line change.
The prices are there because the app is going to put a dollar figure on every call it makes, from the first one. An LLM feature without a cost column is a feature you cannot reason about. Haiku's prices double past 100K input tokens, which InvoiceMini never reaches; the table carries the under-100K rate.
Add the key to .env and an empty line to .env.example:
ANTHROPIC_API_KEY=sk-ant-...
One client in the container
The SDK's Client is built once, from that config, in AppServiceProvider:
use Anthropic\Client;
public function register(): void
{
// One client for the whole request, built from config/claude.php. Anything that
// needs Claude asks the container for Anthropic\Client; tests swap it for a fake.
$this->app->singleton(Client::class, fn () => new Client(
apiKey: config('claude.api_key'),
requestOptions: [
'timeout' => config('claude.timeout'),
'maxRetries' => config('claude.max_retries'),
],
));
}
A singleton because the client holds nothing per request. Bound by its own class rather than an interface because the SDK is the interface: the point of a typed client is to use its types. Anything that needs Claude type-hints Anthropic\Client and the container hands it over; tests bind a different instance, which is the whole testing story below.
The first call
php artisan claude:ping sends one prompt and prints the reply, the stop reason, the token counts and the cost. It proves the key, the model and the network before any feature depends on them, and it is the command you run when something stops working.
<?php
namespace App\Console\Commands;
use Anthropic\Client;
use App\AI\Cost;
use Illuminate\Console\Command;
// The smallest possible round trip: one prompt in, one answer out, and what it cost.
class ClaudePing extends Command
{
// A default with a colon in it would be read as the argument's description, so the
// prompt's default lives in handle() instead of the signature.
protected $signature = 'claude:ping {prompt? : The message to send} {--model= : Model id, default from config}';
protected $description = 'Send one message to Claude and print the reply and its cost';
public function handle(Client $claude): int
{
$model = $this->option('model') ?: config('claude.models.default');
$prompt = $this->argument('prompt') ?? 'In one sentence, what is a Laravel service container?';
$message = $claude->messages->create(
model: $model,
maxTokens: 1024,
messages: [['role' => 'user', 'content' => $prompt]],
);
foreach ($message->content as $block) {
if ($block->type === 'text') {
$this->line($block->text);
}
}
$this->newLine();
$this->table(['model', 'stop reason', 'input tokens', 'output tokens', 'cost'], [[
$message->model,
$message->stopReason,
$message->usage->inputTokens,
$message->usage->outputTokens,
Cost::format(Cost::of($model, $message->usage)),
]]);
return self::SUCCESS;
}
}
Three things in that code are worth a sentence each.
messages->create() takes named arguments in camelCase (maxTokens), and the SDK maps them to the API's snake case on the wire. Copying max_tokens from a cURL example into a named argument is a fatal error, not a silent one, which is the better failure.
The response's content is a list of blocks, not a string. A text reply is one text block, but a reply can also carry thinking blocks and, from part 4, tool_use blocks. Reading $message->content[0]->text works until the day the first block is not text, so the loop checks the type.
maxTokens is a hard ceiling on the reply, and the model does not know it is there. If the reply hits it, stopReason is max_tokens and the text stops mid-sentence. Printing the stop reason on every call is how you notice.
App\AI\Cost is a dozen lines that multiply the token counts by the price table:
final class Cost
{
public static function of(string $model, Usage $usage): float
{
$prices = config("claude.prices.{$model}");
if ($prices === null) {
throw new \InvalidArgumentException("No price configured for model [{$model}].");
}
return $usage->inputTokens * $prices['input'] / 1_000_000
+ $usage->outputTokens * $prices['output'] / 1_000_000;
}
// Six decimals: a Haiku call costs millionths of a dollar and would round to nothing at four.
public static function format(float $dollars): string
{
return '$'.number_format($dollars, 6);
}
}
Run it:
php artisan claude:ping
Laravel's service container is a dependency injection tool that manages class dependencies by automatically resolving and injecting the objects a class needs, so you don't have to instantiate them manually.
+-----------------+-------------+--------------+---------------+-----------+
| model | stop reason | input tokens | output tokens | cost |
+-----------------+-------------+--------------+---------------+-----------+
| claude-opus-5-5 | end_turn | 24 | 82 | $0.001736 |
+-----------------+-------------+--------------+---------------+-----------+
Twenty-four tokens in, eighty-two out, a sixth of a cent. The same prompt with the fast model:
php artisan claude:ping "Reply with the single word pong." --model=claude-haiku-5-5
Pong
+------------------+-------------+--------------+---------------+-----------+
| model | stop reason | input tokens | output tokens | cost |
+------------------+-------------+--------------+---------------+-----------+
| claude-haiku-5-5 | end_turn | 18 | 5 | $0.000004 |
+------------------+-------------+--------------+---------------+-----------+
Four millionths of a dollar. That is the number to remember when part 5 decides which calls go to which model.
A wrong key does not come back as a quiet empty reply. The SDK throws a typed exception with the API's error envelope in it:
ANTHROPIC_API_KEY=sk-ant-wrong php artisan claude:ping
Anthropic\Core\Exceptions\AuthenticationException
Anthropic Authentication Exception
{
"status": 401,
"body": {
"type": "error",
"error": {
"type": "authentication_error",
"message": "invalid x-api-key"
},
"request_id": "req_011CgexT7s7Gt2npKTPiXYRd"
}
}
There is a typed exception per status: AuthenticationException, RateLimitException, BadRequestException, InternalServerException, and APIConnectionException for a network that never answered. Part 5 catches the retryable ones in a queued job; nothing in this part catches anything, because a command that fails loudly is the right behaviour for a command.
Testing without the network
The SDK sends every request through a PSR-18 client it is given. Hand it one that answers from a queue instead of a socket, and a test controls exactly what the API says and can inspect exactly what the app sent. No mocking of the SDK's classes, no HTTP recording library, no Http::fake() (the SDK does not go through Laravel's HTTP client).
tests/Support/FakeClaude.php:
<?php
namespace Tests\Support;
use Anthropic\Client;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
// A PSR-18 client that never touches the network. The SDK sends every request through
// the `transporter` it is given, so a test queues the responses it wants, binds a Client
// built on this fake, and afterwards inspects exactly what the app sent.
final class FakeClaude implements ClientInterface
{
/** @var list<ResponseInterface> */
private array $responses = [];
/** @var list<array{method: string, uri: string, headers: array<string, string>, body: array<string, mixed>}> */
public array $requests = [];
/** Bind a Client that answers from this fake and return the fake for assertions. */
public static function bind(array ...$responses): self
{
$fake = new self;
foreach ($responses as $response) {
$fake->queue($response);
}
app()->instance(Client::class, new Client(
apiKey: 'test-key',
requestOptions: ['transporter' => $fake, 'maxRetries' => 0],
));
return $fake;
}
/** A complete Messages API response with one text block, as the API would send it. */
public static function text(string $text, int $inputTokens = 10, int $outputTokens = 5, string $model = 'claude-opus-5-5'): array
{
return [
'id' => 'msg_test_'.substr(md5($text), 0, 12),
'type' => 'message',
'role' => 'assistant',
'model' => $model,
'content' => [['type' => 'text', 'text' => $text]],
'stop_reason' => 'end_turn',
'stop_sequence' => null,
'usage' => ['input_tokens' => $inputTokens, 'output_tokens' => $outputTokens],
];
}
/** An error the API returns with a status, in the API's error envelope. */
public static function error(int $status, string $type, string $message): array
{
return ['__status' => $status, 'type' => 'error', 'error' => ['type' => $type, 'message' => $message]];
}
public function queue(array $body): void
{
$status = $body['__status'] ?? 200;
unset($body['__status']);
$this->responses[] = new Response($status, ['Content-Type' => 'application/json'], json_encode($body));
}
public function sendRequest(RequestInterface $request): ResponseInterface
{
$this->requests[] = [
'method' => $request->getMethod(),
'uri' => (string) $request->getUri(),
'headers' => array_change_key_case(array_map(fn (array $values) => implode(', ', $values), $request->getHeaders())),
'body' => json_decode((string) $request->getBody(), true) ?? [],
];
return array_shift($this->responses)
?? throw new \LogicException('FakeClaude has no response left for '.$request->getMethod().' '.$request->getUri());
}
public function lastRequest(): array
{
return $this->requests[array_key_last($this->requests)] ?? throw new \LogicException('FakeClaude received no request.');
}
}
The fixture in text() is the wire format, snake case, exactly as the API sends it, because the SDK parses the fake's response the same way it parses a real one. maxRetries is zero so a test that queues a 500 sees one request, not three. bind() replaces the container's singleton with app()->instance(), which is all "swap the client in tests" ever needs to mean.
phpunit.xml gets a key, so the production binding would construct even if a test forgot to call bind():
<env name="ANTHROPIC_API_KEY" value="test-key"/>
The tests, tests/Feature/AI/ClaudePingTest.php:
<?php
use Tests\Support\FakeClaude;
it('prints the reply and what it cost', function () {
FakeClaude::bind(FakeClaude::text('A container that resolves classes.', inputTokens: 20, outputTokens: 8));
$this->artisan('claude:ping')
->expectsOutputToContain('A container that resolves classes.')
->expectsTable(
['model', 'stop reason', 'input tokens', 'output tokens', 'cost'],
[['claude-opus-5-5', 'end_turn', 20, 8, '$0.000240']], // 20 × $4 + 8 × $20, per million
)
->assertSuccessful();
});
it('sends the prompt to the configured model with the key', function () {
$claude = FakeClaude::bind(FakeClaude::text('ok'));
$this->artisan('claude:ping', ['prompt' => 'Say ok']);
$request = $claude->lastRequest();
expect($request['method'])->toBe('POST')
->and($request['uri'])->toBe('https://api.anthropic.com/v1/messages')
->and($request['headers']['authorization'])->toBe('Bearer test-key')
->and($request['headers']['anthropic-version'])->toBe('2026-10-21')
->and($request['body']['model'])->toBe('claude-opus-5-5')
->and($request['body']['max_tokens'])->toBe(1024)
->and($request['body']['messages'])->toBe([['role' => 'user', 'content' => 'Say ok']]);
});
it('uses the fast model when asked', function () {
$claude = FakeClaude::bind(FakeClaude::text('ok', model: 'claude-haiku-5-5'));
$this->artisan('claude:ping', ['--model' => 'claude-haiku-5-5'])->assertSuccessful();
expect($claude->lastRequest()['body']['model'])->toBe('claude-haiku-5-5');
});
it('surfaces an API error instead of swallowing it', function () {
FakeClaude::bind(FakeClaude::error(401, 'authentication_error', 'invalid x-api-key'));
$this->artisan('claude:ping');
})->throws(Anthropic\Core\Exceptions\AuthenticationException::class);
The second test is the one that earns its place. It pins the request the app sends: the endpoint, the API version header, the model, the token ceiling and the message. When the SDK or the config changes, this test says so. It also documents something the cURL examples on the internet have not caught up with: SDK 1.4 sends the key as Authorization: Bearer, not as the x-api-key header, and the server accepts both.
The fourth test queues a 401 body and asserts the typed exception comes out the top of the command. Later parts queue 429s and 529s the same way to test retries.
One architecture rule joins the ones from the testing series:
arch('requests and models never talk to the Claude API directly; that work lives in App\AI')
->expect(['App\Http', 'App\Models'])
->not->toUse('Anthropic');
Controllers call classes in App\AI; those classes call the SDK. Part 2 adds the first of them.
php artisan test --testsuite=Unit,Feature --compact
Tests: 128 passed (306 assertions)
Duration: 16.99s
What went wrong
The "prompt" argument does not exist. The signature was {prompt=Reply with one sentence: what is a Laravel service container?}. Laravel reads : inside a signature token as the separator before an argument's description, so the default ended at the colon and the rest became a description of nothing. The default moved into handle().
Output does not contain "end_turn" although it plainly did when the command ran. expectsOutputToContain does not see rows written by $this->table(); tables have their own assertion, expectsTable, which also checks the cell values.
Undefined array key "x-api-key" in the request assertion. I had asserted the header every tutorial shows. SDK 1.4 sends Authorization: Bearer <key>. The fake also lowercases header names, because PSR-7 preserves whatever case the sender used.
$0.0000 as the cost of the Haiku call. Four decimals were not enough for four millionths of a dollar; Cost::format uses six.
A line of JSON instead of command output inside an AI coding agent, from Laravel 13's laravel/pao package, as in the testing series. PAO_DISABLE=1 in front of every artisan call from an agent.
Part 2 gives the app its first real feature: a plain-English request becomes a validated invoice draft through structured outputs, with the schema generated from a PHP class.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
1 / 6- OverviewAdding a Claude-powered feature to a Laravel app, properly
- Part 1The SDK, one client in the container, and the first call
- Part 2An invoice draft from plain English, through structured outputs
- Part 3A payment reminder streamed into the page
- Part 4An assistant that answers from your own data, through tools
- Part 5Queues, retries, real cost, caching measured, the Batch API and Haiku
- Part 6An eval set, a grader, prompt snapshots and a nightly run