Anthropic Laravel
The Claude companion for Laravel: the Anthropic API behind a facade, with batches, token counting, files, refusal fallback, named connections, events and test fakes, beside laravel/ai.
composer require mozex/anthropic-laravel
Anthropic Laravel is the Claude companion for Laravel. It puts the Anthropic API behind an Anthropic:: facade, the Claude-specific parts a provider-neutral package leaves out included: Message Batches, token counting, the rate-limit headers on every response, and refusal fallback with its fallback credit. It runs on Anthropic PHP, the community-maintained PHP SDK, and sits beside laravel/ai without getting in its way.
Under the hood, every request is handled by the underlying PHP package, so you get full access to every Anthropic API feature (messages, streaming, tool use, extended thinking, web search, code execution, citations, token counting, batches, and files) without the framework-agnostic boilerplate.
Not using Laravel? Use the framework-agnostic Anthropic PHP package directly.
Why this package
One Facade for everything. Anthropic::messages(), Anthropic::models(), Anthropic::batches(), Anthropic::files(), and the deprecated Anthropic::completions(). No factory setup, no client instantiation. The service provider handles it.
Publishable config with env support. Run php artisan anthropic:install once and you've got a config/anthropic.php file, an ANTHROPIC_API_KEY entry in .env (plus the optional settings, commented out), and you're ready to go.
Anthropic::fake() in your tests. Swap the real client with a fake one, queue responses, and assert exactly which requests were sent. This pairs with Laravel's existing testing idioms (Event::fake(), Queue::fake()) so your test code stays consistent.
Batches the Laravel way. Anthropic::batch($requests)->then(...)->dispatch() sends a Message Batch at half the price and queues a job that polls it until it ends, with an event per result. See Batches.
Connections, tenants and the Admin API. Name connections in the config and reach them with Anthropic::connection(), build a client for a tenant's key with Anthropic::withApiKey(), and use Anthropic::organization() for the Admin API. One Anthropic::fake() answers all of them. See Configuration.
Built for production. Events for every request, request IDs in your logs and error tracker, optional Context, Telescope and Nightwatch recording, and php artisan anthropic:doctor to catch a queue that would run a Claude call twice. See Diagnostics.
Same-day support for new API features. Parameters pass through to the API as-is. New content block types, new thinking modes, new tool versions all work the day Anthropic ships them. You don't wait for a package update.
Installation
Requires PHP 8.2+ - see all version requirements
Install via Composer:
composer require mozex/anthropic-laravel
Run the install command:
php artisan anthropic:install
This publishes config/anthropic.php to your project and adds ANTHROPIC_API_KEY= to your .env file, with the optional settings commented out. Fill in your key from the Anthropic Console:
ANTHROPIC_API_KEY=sk-ant-...
That's the whole setup. The service provider registers the client as a singleton in the container, so you can start using the Facade right away.
Quick start
Use the Anthropic Facade anywhere in your app:
use Anthropic\Laravel\Facades\Anthropic;
$response = Anthropic::messages()->create([
'model' => 'claude-sonnet-5-5',
'max_tokens' => 1024,
'messages' => [
['role' => 'user', 'content' => 'Hello!'],
],
]);
echo $response->content[0]->text; // Hello! How can I assist you today?
The response is a typed, readonly object with properties for the message ID, model, content blocks, token usage, and stop reason:
$response->id; // 'msg_01BSy0WCV7QR2adFBauynAX7'
$response->model; // 'claude-sonnet-5-5'
$response->stop_reason; // 'end_turn'
$response->usage->inputTokens; // 10
$response->usage->outputTokens; // 19
Configuration
For most apps, the two env vars are enough:
ANTHROPIC_API_KEY=sk-ant-...
ANTHROPIC_REQUEST_TIMEOUT=30
The request timeout defaults to 30 seconds. For long-running requests (large context windows, extended thinking, code execution), bump it up. See Configuration for details.
Testing
In your tests, swap the real client with a fake using Anthropic::fake():
use Anthropic\Laravel\Facades\Anthropic;
use Anthropic\Resources\Messages;
use Anthropic\Responses\Messages\CreateResponse;
Anthropic::fake([
CreateResponse::fake([
'content' => [['type' => 'text', 'text' => 'Paris is the capital of France.']],
]),
]);
// Run your code...
$this->post('/ask', ['question' => 'What is the capital of France?']);
// Then assert what was sent
Anthropic::assertSent(Messages::class, function (string $method, array $parameters): bool {
return $method === 'create' && $parameters['model'] === 'claude-sonnet-5-5';
});
See Testing for the full set of fake patterns and assertions.
What's covered
Usage covers all API operations:
- Messages: Send messages and read responses
- Streaming: Stream responses token by token, straight to the browser
- Tool Use: Give Claude custom functions to call
- Thinking: Adaptive and extended thinking for complex reasoning
- Server Tools: Web search and sandboxed code execution
- Citations: Source citations from documents and web search
- Token Counting: Count tokens before sending
- Models: List and inspect available models
- Batches: Process large volumes of requests asynchronously
- Usage Ledger: Record every call's tokens, billed to a user, team or feature
- Token Budgets: Cap the tokens a user or team spends, refusing calls before they're sent
- Files: Upload documents once, reference them by
file_idin later requests - Completions: The deprecated Text Completions API
- Raw Requests: Call an endpoint the package has no method for yet
Reference covers cross-cutting concerns:
- Configuration: Config file, env vars, timeouts, container binding
- Error Handling: Exception types and catching them in Laravel
- Meta Information: Rate limits, request IDs, token limits
- Testing:
Anthropic::fake(), mock responses, and assertions - Using alongside laravel/ai: One key for both, and what to reach for where
- Diagnostics:
anthropic:doctor, theaboutsection, and a health check that never calls the API