Adding a Claude-powered feature to a Laravel app, properly · Part 2 of 6
An invoice draft from plain English, through structured outputs
A JSON schema derived from a PHP class, the API guaranteeing the shape, the company's data in the system prompt, and a form that fills itself in for review.
By Abhishek Fouzdar
This part gives InvoiceMini its first real Claude feature. On the new-invoice page you type "Roberts PLC: 3 days of on-site training at 900 per day, 10% off, payable in GBP", and the form fills itself in for you to check. It ends with the feature working against the real API, eight feature tests and a dataset of unit tests that run without it, and a cost of about seven tenths of a cent per draft. Part 1 set up the SDK, the client and the fake.

The problem with asking for JSON
The naive version of this feature asks the model to "reply with JSON" and parses what comes back. It works most of the time, and most of the time is the problem: one day the reply has a sentence before the JSON, or a trailing comma, or a key you did not ask for, or a price as a string. Every one of those is a parse error at 4 pm on a Friday.
Structured outputs move that problem to the API. You send a JSON schema with the request, and the response is guaranteed to be valid JSON that matches the schema. No prose, no missing required keys, no wrong types. The model still decides the values; the shape is no longer its decision.
The PHP SDK goes one step further: the schema comes from a PHP class. You write the class you want to receive, and the SDK derives the schema from its typed properties.
The draft as a class
app/AI/InvoiceDraft.php:
<?php
namespace App\AI;
use Anthropic\Core\Attributes\Required;
use Anthropic\Lib\Attributes\Constrained;
use Anthropic\Lib\Concerns\StructuredOutputModelTrait;
use Anthropic\Lib\Contracts\StructuredOutputModel;
use App\Models\Client;
use App\Models\Company;
use Illuminate\Support\Collection;
// The shape the model must fill in. The SDK turns this class into a JSON schema and the API
// guarantees the reply matches it, so the app never parses prose and never sees a missing key.
final class InvoiceDraft implements StructuredOutputModel
{
use StructuredOutputModelTrait;
#[Constrained(description: 'The client, copied exactly from the list of known clients. Omit this field if the text names none of them')]
public ?string $clientName = null;
#[Required(enum: ['EUR', 'USD', 'GBP', 'JPY'])]
#[Constrained(description: 'Invoice currency; the company default unless the text says otherwise')]
public string $currency;
#[Constrained(description: 'Whole-invoice discount in percent; 0 when none is mentioned')]
public float $discountPercent = 0;
#[Constrained(description: 'The invoice lines, in the order they were described', itemClass: DraftLine::class, minItems: 1)]
public array $lines;
#[Constrained(description: 'Notes for the invoice footer. Omit this field unless the text asks for some')]
public ?string $notes = null;
#[Constrained(description: 'Anything in the text that could not be turned into a field: an unknown client, a line without a price, an unsupported currency. One short sentence each. Omit this field when everything mapped')]
public ?string $unresolved = null;
/**
* The draft as the invoice form expects it, so the form can be prefilled through old()
* input. Client names are matched case-insensitively against the company's clients.
*
* @param Collection<int, Client> $clients
*/
public function toFormInput(Company $company, Collection $clients): array
{
// The model sometimes sends "" where the schema allows null; both mean "no client".
$name = trim((string) $this->clientName);
$client = $name === ''
? null
: $clients->first(fn (Client $c) => strcasecmp($c->name, $name) === 0);
return [
'client_id' => $client?->id,
'currency' => $this->currency,
'discount_percent' => $this->discountPercent,
'notes' => $this->notes,
'lines' => array_map(fn (DraftLine $line) => [
'description' => $line->description,
'quantity' => $line->quantity,
'unit_price' => $line->unitPriceMinor($this->currency),
'tax_rate' => $line->taxRate ?? (float) $company->default_tax_rate,
], $this->lines),
];
}
}
The rules the SDK applies are simple and worth knowing. A typed property becomes a schema property of that type. A property with a default, or a nullable type, becomes optional; everything else is required. #[Constrained(description:)] is the sentence the model reads when deciding what to put there, and it is the most important line of each property. #[Required(enum:)] restricts a string to a fixed list, which is how currency can never come back as "euros". itemClass makes lines an array of another structured class, DraftLine:
final class DraftLine implements StructuredOutputModel
{
use StructuredOutputModelTrait;
#[Constrained(description: 'What was sold, as it should appear on the invoice')]
public string $description;
#[Constrained(description: 'How many; 1 for a flat fee')]
public float $quantity;
#[Constrained(description: 'Price per unit in major currency units, e.g. 150.00; 0 if the text gives no price')]
public float $unitPrice;
#[Constrained(description: 'Tax rate in percent for this line. Omit this field to use the company default')]
public ?float $taxRate = null;
public function unitPriceMinor(string $currency): int
{
return (int) round($this->unitPrice * 10 ** Money::decimals($currency));
}
}
Prices come back in major units, 150.00 rather than 15000, because that is how people write them and how the model reads them. InvoiceMini stores minor units, so unitPriceMinor() converts with the per-currency decimals from the testing series' Money class: 150 euros is 15000, 12000 yen is 12000, and a rounding step keeps 19.999 from becoming 1999 cents.
Two fields exist for the person rather than the data. clientName is a name, not an id, because the model should never see or invent ids; the app maps the name to a client of the right company afterwards. unresolved is where the model puts what it could not map, in sentences. That turns "the model guessed" into "the model told you it was unsure", which is the difference between a feature people trust and one they turn off.
This is the schema the SDK sends, printed with Anthropic\Lib\Helpers\StructuredOutput::toJsonSchema(InvoiceDraft::class), trimmed to the top level:
{
"type": "object",
"properties": {
"clientName": { "type": "string", "description": "The client, copied exactly from the list of known clients. Omit this field if the text names none of them" },
"currency": { "type": "string", "enum": ["EUR", "USD", "GBP", "JPY"], "description": "Invoice currency; the company default unless the text says otherwise" },
"discountPercent": { "type": "number", "default": 0, "description": "Whole-invoice discount in percent; 0 when none is mentioned" },
"lines": { "type": "array", "items": { "type": "object", "..." : "..." }, "minItems": 1, "description": "The invoice lines, in the order they were described" },
"notes": { "type": "string", "description": "Notes for the invoice footer. Omit this field unless the text asks for some" },
"unresolved": { "type": "string", "description": "..." }
},
"required": ["currency", "discountPercent", "lines"],
"additionalProperties": false
}
Notice what a nullable PHP property became: an optional string, not a string that may be null. That matters, and it bit me; see what went wrong.
The drafter
app/AI/InvoiceDrafter.php is the class controllers call. It is the only place in this part that touches the SDK:
<?php
namespace App\AI;
use Anthropic\Client;
use Anthropic\Core\Exceptions\APIConnectionException;
use Anthropic\Core\Exceptions\APIStatusException;
use App\Models\Company;
use Illuminate\Support\Facades\Log;
// Turns a plain-English request into an InvoiceDraft for one company. The company's own
// data (clients, defaults, today's date) goes in the system prompt; the user's text is the
// only user message. The API fills the InvoiceDraft schema; this class does the rest.
final class InvoiceDrafter
{
public function __construct(private Client $claude) {}
public function draft(Company $company, string $request): InvoiceDraft
{
$model = config('claude.models.default');
try {
$message = $this->claude->messages->create(
model: $model,
maxTokens: 2048,
system: $this->systemPrompt($company),
messages: [['role' => 'user', 'content' => $request]],
// Extraction needs no deliberation: low effort is faster and cheaper, and the
// schema, not the reasoning, is what makes the output correct.
outputConfig: ['format' => InvoiceDraft::class, 'effort' => 'low'],
);
} catch (APIStatusException|APIConnectionException $e) {
throw new DraftFailed('Claude could not draft the invoice: '.$e->getMessage(), previous: $e);
}
if ($message->stopReason !== 'end_turn') {
throw new DraftFailed("Claude stopped early ({$message->stopReason}); the draft is incomplete.");
}
Log::info('claude.draft', [
'company_id' => $company->id,
'model' => $model,
'input_tokens' => $message->usage->inputTokens,
'output_tokens' => $message->usage->outputTokens,
'cost' => Cost::of($model, $message->usage),
]);
$draft = $message->parsedOutput();
if (! $draft instanceof InvoiceDraft) {
throw new DraftFailed('Claude returned something that is not an invoice draft.');
}
return $draft;
}
private function systemPrompt(Company $company): string
{
$clients = $company->clients()->orderBy('name')->pluck('name')
->map(fn (string $name) => "- {$name}")
->implode("\n");
// The decimal cast gives "20.00"; the prompt reads better as "20".
$taxRate = (float) $company->default_tax_rate;
return <<<PROMPT
You draft invoices for {$company->name} from a short description written by one of its staff.
Fill the schema from the description and nothing else. Do not invent lines, prices or clients.
Known clients (use the name exactly as written; omit the client if the description names none of them):
{$clients}
Company defaults: currency {$company->currency}, tax rate {$taxRate}% on every line unless the description gives another rate.
Today is {$company->freshTimestamp()->toDateString()}.
Prices are per unit in major currency units (write 150.00 for one hundred and fifty). Hours, days and items are quantities; a flat fee is quantity 1.
Put anything you could not map into `unresolved`, one short sentence per problem, so the person can fix it. Omit it when everything mapped.
PROMPT;
}
}
Walking through the request. system carries everything the model needs that the person did not type: the company, its clients by name, its defaults, the date. The user message is the person's text and nothing else, which keeps the two apart; part 4 explains why that separation is also a security boundary. outputConfig carries the class as format, and effort: 'low'. Opus 5.5 thinks before it answers and its default effort is medium; extraction into a schema is not a task that improves with deliberation, and low effort makes the call faster and cheaper without changing what the schema guarantees. Part 5 measures the difference.
parsedOutput() returns an InvoiceDraft instance built from the JSON; the instanceof check after it is for the type checker and for the day someone changes the format and forgets this line.
Two failure paths are explicit. The SDK's typed exceptions are caught and rethrown as DraftFailed, a two-line RuntimeException in App\AI, so the controller never imports the SDK and the architecture test from part 1 keeps passing. And a stop reason other than end_turn is treated as a failure: if the reply hit maxTokens the JSON is cut off, and a schema cannot guarantee anything about half a document.
Every call logs its tokens and cost. In part 5 that log line becomes a table; for now it is the number in the title of this section.
The controller and the form
The route sits next to the invoice resource, and the controller does nothing clever: validate the text, draft, redirect back to the form with the draft as old input.
Route::post('/invoices/draft', InvoiceDraftController::class)->name('invoices.draft');
class InvoiceDraftController extends Controller
{
public function __invoke(Request $request, InvoiceDrafter $drafter): RedirectResponse
{
Gate::authorize('create', Invoice::class);
$validated = $request->validate(['description' => ['required', 'string', 'min:10', 'max:2000']]);
$company = $request->user()->company;
try {
$draft = $drafter->draft($company, $validated['description']);
} catch (DraftFailed $e) {
report($e);
return redirect()->route('invoices.create')
->withInput($validated)
->with('draft_error', 'Drafting failed. Fill the form by hand, or try again in a moment.');
}
return redirect()->route('invoices.create')
->withInput($draft->toFormInput($company, $company->clients))
->with('status', 'Draft filled in from your description. Check every field before creating the invoice.')
->with('draft_unresolved', $draft->unresolved);
}
}
Nothing is saved. The draft travels as flashed input, the existing form reads it through old() exactly as it reads a failed validation, and the person reviews every field before "Create draft" writes anything. The AI fills forms; people submit them. That one decision removes most of the ways this feature could do damage.
The form itself grows a box above the fields, only on the create page:

@unless ($invoice->exists)
<form method="post" action="{{ route('invoices.draft') }}" class="mb-8 rounded-md border border-zinc-200 bg-zinc-50 p-4" id="draft-form">
@csrf
<label for="description" class="block text-sm font-medium">Describe the invoice</label>
<textarea id="description" name="description" rows="2" placeholder="e.g. Invoice Acme for 12 hours of consulting at 150 an hour and a 300 setup fee"
class="mt-1 w-full rounded-md border border-zinc-300 px-3 py-2">{{ old('description') }}</textarea>
@error('description') <p class="mt-1 text-sm text-red-700">{{ $message }}</p> @enderror
<div class="mt-2 flex items-center gap-3">
<button type="submit" class="rounded-md border border-zinc-900 px-3 py-1.5 text-sm">Draft with Claude</button>
@if (session('draft_error')) <p class="text-sm text-red-700" role="alert">{{ session('draft_error') }}</p> @endif
</div>
@if (session('draft_unresolved'))
<p class="mt-3 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900" role="alert">
<span class="font-medium">Could not fill in:</span> {{ session('draft_unresolved') }}
</p>
@endif
</form>
@endunless
Against the real API
The demo company is Acme Studio, in euros, with three clients: Von-Blick, Bahringer and Sons, Roberts PLC. The sentence from the screenshot, through InvoiceDrafter directly:
Roberts PLC: 3 days of on-site training at 900 per day, 10% off, payable in GBP. Add a note that travel is billed separately.
{
"clientName": "Roberts PLC",
"currency": "GBP",
"discountPercent": 10,
"lines": [
{ "description": "On-site training", "quantity": 3, "unitPrice": 900, "taxRate": 20 }
],
"notes": "Travel is billed separately."
}
Every field right, the tax rate taken from the company default, and unresolved omitted because nothing was. Through the browser the round trip, from clicking the button to the prefilled form, took 2.5 seconds.
A sentence that names a client the company does not have:
Invoice Acme for 12 hours of consulting at 150 an hour and a 300 setup fee with no tax on the fee
{
"clientName": "",
"currency": "EUR",
"discountPercent": 0,
"lines": [
{ "description": "Consulting", "quantity": 12, "unitPrice": 150, "taxRate": 20 },
{ "description": "Setup fee", "quantity": 1, "unitPrice": 300, "taxRate": 0 }
],
"notes": null,
"unresolved": "The client 'Acme' is not a known client (Acme Studio is the issuing company); please specify the client."
}
The lines are right, including the zero tax on the fee, the client is left empty, and the reason is a sentence the person can act on. It even noticed that "Acme" is the company's own name. The form shows the lines filled in, the client dropdown on "Choose…", and the amber box with that sentence.
The log line for each of those calls:
local.INFO: claude.draft {"company_id":1,"model":"claude-opus-5-5","input_tokens":1090,"output_tokens":144,"cost":0.00724}
local.INFO: claude.draft {"company_id":1,"model":"claude-opus-5-5","input_tokens":1098,"output_tokens":129,"cost":0.006972}
Seven tenths of a cent a draft, and most of it is input: the schema and the system prompt are about a thousand tokens and the person's sentence is thirty. Those thousand tokens are the same on every call, which is what prompt caching is for, in part 5.
Testing it
The fake from part 1 gets one more constructor, a structured-output reply, which on the wire is just the JSON inside a text block:
/** A structured-output response: the JSON the schema asked for, inside one text block. */
public static function json(array $data, int $inputTokens = 10, int $outputTokens = 5): array
{
return self::text(json_encode($data), $inputTokens, $outputTokens);
}
tests/Feature/AI/InvoiceDraftTest.php has eight tests. The first proves the whole flow, including that the form really renders the flashed input:
it('prefills the form from the draft', function () use ($acmeDraft) {
FakeClaude::bind(FakeClaude::json($acmeDraft()));
$this->actingAs($this->user)
->post(route('invoices.draft'), ['description' => 'Invoice Acme for 12 hours of consulting at 150 an hour and a 300 setup fee'])
->assertRedirect(route('invoices.create'))
->assertSessionHas('status')
->assertSessionHasInput('client_id', $this->acme->id)
->assertSessionHasInput('currency', 'EUR')
->assertSessionHasInput('lines', [
['description' => 'Consulting', 'quantity' => 12.0, 'unit_price' => 15000, 'tax_rate' => 20.0],
['description' => 'Setup fee', 'quantity' => 1.0, 'unit_price' => 30000, 'tax_rate' => 0.0],
]);
// And the form really shows it.
$this->actingAs($this->user)->get(route('invoices.create'))
->assertSee('Draft filled in from your description')
->assertSee('value="Consulting"', escape: false)
->assertSee('value="15000"', escape: false);
});
The second pins the request, which is the test that catches a broken prompt or a changed schema before a person does:
it('asks for the draft schema, with the company context in the system prompt', function () use ($acmeDraft) {
$claude = FakeClaude::bind(FakeClaude::json($acmeDraft()));
$this->actingAs($this->user)->post(route('invoices.draft'), ['description' => 'Invoice Acme for 12 hours of consulting at 150']);
$body = $claude->lastRequest()['body'];
expect($body['model'])->toBe('claude-opus-5-5')
->and($body['output_config']['effort'])->toBe('low')
->and($body['output_config']['format']['type'])->toBe('json_schema')
->and($body['output_config']['format']['schema']['required'])->toContain('currency', 'lines')
->and($body['output_config']['format']['schema']['properties']['currency']['enum'])->toBe(['EUR', 'USD', 'GBP', 'JPY'])
->and($body['output_config']['format']['schema']['properties']['lines']['items']['properties'])->toHaveKeys(['description', 'quantity', 'unitPrice'])
->and($body['system'])->toContain('- Acme GmbH')
->and($body['system'])->toContain('currency EUR, tax rate 20%')
->and($body['messages'])->toBe([['role' => 'user', 'content' => 'Invoice Acme for 12 hours of consulting at 150']]);
});
The rest cover the edges: a client the model names that belongs to another company is never matched, an unknown client leaves the field empty and flashes the reason (for both null and "", which is a dataset), an API error becomes a message on the form rather than a 500, a max_tokens stop is a failure, a too-short description is rejected before a token is spent, and the route needs a login. The unit side is a dataset on DraftLine::unitPriceMinor() for euros, dollars, yen and dinar.
php artisan test --testsuite=Unit,Feature --compact
Tests: 141 passed (354 assertions)
Duration: 15.01s
What went wrong
"clientName": "" in the first real reply, where I expected null. A nullable PHP property becomes an optional schema property, not a nullable one: "type": "string", no null allowed. Asked for a client it did not have, the model obeyed the schema and sent the closest legal thing, an empty string. Two fixes, both kept: the descriptions now say "omit this field" instead of "null", and toFormInput() treats an empty name as no name. The test for the unknown-client case runs with both values.
Expected ... to contain "currency EUR, tax rate 20%" in the prompt test. Eloquent's decimal:2 cast made the rate 20.00, so the prompt said "20.00%". A float cast in the prompt builder. Small, but every prompt is a string somebody will read, and a prompt that reads badly gets worse answers.
Session is missing expected key [client_id] when asserting the client was left empty. assertSessionHasInput('client_id', null) cannot pass: Laravel's old-input check treats a null value as absent. The test reads session()->getOldInput('client_id') and asserts null directly.
Call to undefined method App\AI\InvoiceDraft::toArray() in a script printing a draft. Structured output models have jsonSerialize(), toJson() and fromArray(), not toArray().
Part 3 puts the API on the other side of the screen: a payment reminder written by Claude, streamed into the page word by word, with the server-sent events, the disconnects and the stop reasons handled rather than hoped about.
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
2 / 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