mozex / 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.
Fund package maintenance!
Requires
- php: ^8.2.0
- guzzlehttp/guzzle: ^7.9.3
- laravel/framework: ^12.69|^13.30
- mozex/anthropic-php: ^1.14.0
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/nightwatch: ^1.30.6
- laravel/pint: ^1.22.0
- laravel/telescope: ^5.26.0
- orchestra/testbench: ^10.0|^11.0
- pestphp/pest: ^3.8.2|^4.0.0|^5.0.0
- pestphp/pest-plugin-laravel: ^3.2|^4.0.0|^5.0.1
- pestphp/pest-plugin-type-coverage: ^3.5|^4.0.0|^5.0.1
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
- symfony/var-dumper: ^7.2.6
Suggests
- laravel/nightwatch: Records the client's requests as outgoing requests, attached on its own (http.nightwatch)
- laravel/telescope: Records each request as a tagged client request entry (http.telescope)
Provides
None
Conflicts
None
Replaces
None
README
Anthropic Laravel
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. Named connections, per-tenant keys, events for every request and one Anthropic::fake() for all of them come with it. It runs on Anthropic PHP, the community-maintained PHP SDK, and sits beside laravel/ai without getting in its way.
Read the full documentation at mozex.dev: searchable docs, version requirements, detailed changelog, and more.
Not using Laravel? Use the framework-agnostic Anthropic PHP package directly.
Table of Contents
- Introduction
- Usage
- Reference
Support This Project
I maintain this package along with several other open-source PHP packages used by thousands of developers every day.
If my packages save you time or help your business, consider sponsoring my work on GitHub Sponsors. Your support lets me keep these packages updated, respond to issues quickly, and ship new features.
Business sponsors get logo placement in package READMEs. See sponsorship tiers →
Why This Package
Anthropic:: Facade for everything. Anthropic::messages(), Anthropic::models(), Anthropic::batches(), Anthropic::files(), and the deprecated Anthropic::completions(). No client instantiation, no factory setup. The service provider handles it.
Anthropic::fake() in your tests. Swap the real client with a fake, queue responses, and assert exactly which requests were sent. Pairs with Laravel's existing testing idioms like Event::fake() and Queue::fake(). See the testing docs →
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... Anthropic::assertSent(Messages::class, function (string $method, array $parameters) { return $parameters['model'] === 'claude-sonnet-5-5'; });
Batches the Laravel way. Anthropic::batch($requests)->then(fn ($batch) => ...)->dispatch() sends a Message Batch at half the price and queues a job that polls it until it ends, then hands each result to a BatchResultReceived listener and runs your callback. See batches →
Named connections and tenant keys. Anthropic::connection('support') gives a client of its own settings, Anthropic::withApiKey($tenant->anthropic_key) one for a key known only at runtime, and Anthropic::organization() the Admin API's. See connections →
Your logs, Telescope and Nightwatch see the calls. Every request dispatches events without a credential in them, a logged API error carries its request ID, Context can carry the IDs into every log line, Telescope can record tagged entries, and Nightwatch picks the calls up on its own. See the configuration docs →
A usage ledger of your own. With ANTHROPIC_LEDGER=true, every billed call, stream and batch result writes its tokens to a table, billed to who Anthropic::for($user, feature: 'summaries') named, and php artisan anthropic:usage sums it by model, feature, user or day. Anthropic::budget('user:'.$id)->perDay(200_000)->enforce() (or the anthropic.budget route middleware) caps the tokens each user spends, refusing calls before they're sent. See the usage ledger → See token budgets →
Queued jobs that know Claude's errors. ThrottlesAnthropic job middleware fails a job on the monthly spend cap (with a SpendCapReached event) and on errors a retry can't fix, releases it on rate limits and overloads for as long as the API asks, and holds back every job of the same model key meanwhile. See retries →
php artisan anthropic:doctor. Checks the key, one API call that spends no tokens, your queues' retry_after against the longest call, and your fallback models' lifecycle, and exits non-zero on a failure so CI can run it. See diagnostics →
One artisan command to set up. php artisan anthropic:install publishes the config file and adds ANTHROPIC_API_KEY= to your .env, with the optional variables commented out. You're ready to go.
Forward-compatible. Parameters pass through to the API as-is. When Anthropic ships a new feature, it works in your code the same day. No waiting for a package update.
Full Anthropic API coverage. Messages, streaming, tool use, extended thinking, web search, code execution, citations, token counting, and batch processing. Every feature the API supports is available through the Facade.
Installation
Requires PHP 8.2+ - see all version requirements
composer require mozex/anthropic-laravel
Run the install command:
php artisan anthropic:install
This publishes config/anthropic.php and adds ANTHROPIC_API_KEY= to your .env, plus the optional settings, commented out. Set your key from the Anthropic Console:
ANTHROPIC_API_KEY=sk-ant-...
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?
Streaming
Print text as it arrives:
$stream = Anthropic::messages()->createStreamed([ 'model' => 'claude-sonnet-5-5', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Tell me a short story.'], ], ]); foreach ($stream as $response) { if ($response->type === 'content_block_delta' && $response->delta->type === 'text_delta') { echo $response->delta->text; } }
Tool Use
Give Claude tools to call, execute them in your code, send results back:
$response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-5-5', 'max_tokens' => 1024, 'tools' => [ [ 'name' => 'get_weather', 'description' => 'Get the current weather in a given location', 'input_schema' => [ 'type' => 'object', 'properties' => [ 'location' => ['type' => 'string'], ], 'required' => ['location'], ], ], ], 'messages' => [ ['role' => 'user', 'content' => 'What is the weather in San Francisco?'], ], ]); $response->content[1]->name; // 'get_weather' $response->content[1]->input['location']; // 'San Francisco'
Extended Thinking
Let Claude reason through complex problems before answering:
$response = Anthropic::messages()->create([ 'model' => 'claude-opus-5-5', 'max_tokens' => 16000, 'thinking' => ['type' => 'adaptive', 'display' => 'summarized'], 'messages' => [ ['role' => 'user', 'content' => 'What is the GCD of 1071 and 462?'], ], ]); $response->content[0]->thinking; // 'Using the Euclidean algorithm...' $response->content[1]->text; // 'The GCD of 1071 and 462 is 21.'
The full documentation covers every feature: vision and images, web search and code execution, document citations, batch processing, error handling, testing, and more.
Resources
Visit the documentation site for searchable docs auto-updated from this repository.
- AI Integration: Use this package with AI coding assistants via Context7 and Laravel Boost
- Requirements: PHP, Laravel, and dependency versions
- Changelog: Release history with linked pull requests and diffs
- Contributing: Development setup, code quality, and PR guidelines
- Questions & Issues: Bug reports, feature requests, and help
- Security: Report vulnerabilities directly via email
License
The MIT License (MIT). Please see License File for more information.
