PHPackages                             goldenpathdigital/laravel-claude - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. goldenpathdigital/laravel-claude

ActiveLibrary[API Development](/categories/api)

goldenpathdigital/laravel-claude
================================

Laravel wrapper for official Anthropic PHP SDK with first-class MCP connector support

v1.2.0(4mo ago)301MITPHPPHP ^8.2CI passing

Since Dec 29Pushed 4mo agoCompare

[ Source](https://github.com/goldenpathdigital/laravel-claude)[ Packagist](https://packagist.org/packages/goldenpathdigital/laravel-claude)[ RSS](/packages/goldenpathdigital-laravel-claude/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (7)Versions (7)Used By (0)

Laravel Claude
==============

[](#laravel-claude)

[![CI](https://github.com/goldenpathdigital/laravel-claude/actions/workflows/ci.yml/badge.svg)](https://github.com/goldenpathdigital/laravel-claude/actions/workflows/ci.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/2e22e6e9cba257cc29490d44bef95144504d4ebd7f1d4955a4075953615a4641/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f676f6c64656e706174686469676974616c2f6c61726176656c2d636c617564652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/goldenpathdigital/laravel-claude)[![Total Downloads](https://camo.githubusercontent.com/0fd423ba513bec6354eded4700bd050b04aef324bbc45a52ef5a89bc9b502686/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f676f6c64656e706174686469676974616c2f6c61726176656c2d636c617564652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/goldenpathdigital/laravel-claude)[![License](https://camo.githubusercontent.com/dde274197fa0d3fa341b7198f14c4e0fd75dcf2d7c2893a5580976a3f3ebb18e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f676f6c64656e706174686469676974616c2f6c61726176656c2d636c617564652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/goldenpathdigital/laravel-claude)

A Laravel wrapper for the official [Anthropic PHP SDK](https://github.com/anthropics/anthropic-sdk-php) with first-class MCP connector support.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
    - [Direct SDK Access](#direct-sdk-access)
    - [Models API](#models-api)
    - [Message Batches API](#message-batches-api)
    - [Files API](#files-api)
    - [Token Counting](#token-counting)
    - [Cost Estimation](#cost-estimation)
    - [Fluent Conversation Builder](#fluent-conversation-builder)
    - [Multi-turn Conversations](#multi-turn-conversations)
    - [Image Support](#image-support)
    - [PDF Documents](#pdf-documents)
    - [Advanced Parameters](#advanced-parameters)
    - [Streaming](#streaming)
    - [Tools](#tools)
    - [MCP Connector](#mcp-connector)
    - [Extended Thinking](#extended-thinking)
    - [Prompt Caching](#prompt-caching)
    - [Structured Outputs](#structured-outputs)
- [Testing](#testing)
    - [Available Assertions](#available-assertions)
    - [Faking Tool Use Responses](#faking-tool-use-responses)
- [Configuration](#configuration)
    - [Queue Integration](#queue-integration)
- [License](#license)

Features
--------

[](#features)

- **Official SDK** — Wraps [`anthropic-ai/sdk`](https://github.com/anthropics/anthropic-sdk-php), not a custom HTTP implementation
- **Laravel Native** — Facades, config, service provider, auto-discovery
- **Fluent API** — Chainable conversation builder with image support
- **Full API Coverage** — Messages, Models, Batches, Files, Token Counting
- **Tool System** — Define tools with fluent builder and automatic execution loop
- **MCP Connector** — First Laravel package with [MCP](https://modelcontextprotocol.io/) client support
- **Streaming** — Real-time streaming with Laravel events
- **Extended Thinking** — Access Claude's reasoning process with budget tokens
- **Prompt Caching** — Reduce costs with cached system prompts
- **Structured Outputs** — JSON schema validation for responses
- **Queue Integration** — Process conversations in background jobs with retry handling
- **Testing Utilities** — `Claude::fake()` with assertion helpers

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 10, 11, or 12

Installation
------------

[](#installation)

```
composer require goldenpathdigital/laravel-claude
```

Publish the config file:

```
php artisan vendor:publish --tag=claude-config
```

Add your API key to `.env`:

```
ANTHROPIC_API_KEY=your-api-key
```

Usage
-----

[](#usage)

### Direct SDK Access

[](#direct-sdk-access)

```
use GoldenPathDigital\Claude\Facades\Claude;

$response = Claude::messages()->create([
    'model' => 'claude-sonnet-4-5-20250929',
    'max_tokens' => 1024,
    'messages' => [
        ['role' => 'user', 'content' => 'Hello, Claude!'],
    ],
]);

echo $response->content[0]->text;
```

### Models API

[](#models-api)

List and retrieve available Claude models:

```
use GoldenPathDigital\Claude\Facades\Claude;

// List all available models
$models = Claude::models()->list([]);

foreach ($models as $model) {
    echo $model->id . ' - ' . $model->display_name;
}

// Get a specific model
$model = Claude::models()->retrieve('claude-sonnet-4-5-20250929', []);
echo $model->display_name;
```

### Message Batches API

[](#message-batches-api)

Process multiple messages in batch for high-throughput workloads:

```
use GoldenPathDigital\Claude\Facades\Claude;

// Create a batch
$batch = Claude::batches()->create([
    'requests' => [
        [
            'custom_id' => 'request-1',
            'params' => [
                'model' => 'claude-sonnet-4-5-20250929',
                'max_tokens' => 1024,
                'messages' => [['role' => 'user', 'content' => 'Hello!']],
            ],
        ],
        [
            'custom_id' => 'request-2',
            'params' => [
                'model' => 'claude-sonnet-4-5-20250929',
                'max_tokens' => 1024,
                'messages' => [['role' => 'user', 'content' => 'How are you?']],
            ],
        ],
    ],
]);

// Check batch status
$batch = Claude::batches()->retrieve($batch->id, []);
echo $batch->processing_status;

// List all batches
$batches = Claude::batches()->list([]);

// Get results when complete
$results = Claude::batches()->results($batch->id, []);

// Cancel a batch
Claude::batches()->cancel($batch->id, []);

// Delete a completed batch
Claude::batches()->delete($batch->id, []);
```

### Files API

[](#files-api)

Manage files uploaded to the Anthropic API:

```
use GoldenPathDigital\Claude\Facades\Claude;

// List all files
$files = Claude::files()->list([]);

foreach ($files as $file) {
    echo $file->id . ' - ' . $file->filename;
}

// Get file metadata
$file = Claude::files()->retrieveMetadata($fileId, []);

// Delete a file
Claude::files()->delete($fileId, []);
```

### Token Counting

[](#token-counting)

Count tokens before sending a request:

```
use GoldenPathDigital\Claude\Facades\Claude;

$count = Claude::countTokens([
    'model' => 'claude-sonnet-4-5-20250929',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello, how are you?'],
    ],
]);

echo "Input tokens: " . $count->input_tokens;
```

### Cost Estimation

[](#cost-estimation)

Estimate API costs based on token usage:

```
use GoldenPathDigital\Claude\Facades\Claude;

// Estimate cost for a request
$cost = Claude::estimateCost(
    inputTokens: 1000,
    outputTokens: 500,
    model: 'claude-sonnet-4-5-20250929'
);

echo $cost->formatted();        // "$0.010500"
echo $cost->total();            // 0.0105
echo $cost->inputCost;          // 0.003
echo $cost->outputCost;         // 0.0075
echo $cost->totalTokens();      // 1500

// Get pricing for a model
$pricing = Claude::getPricingForModel('claude-opus-4-20250514');
// ['input' => 15.00, 'output' => 75.00] (per million tokens)
```

### Fluent Conversation Builder

[](#fluent-conversation-builder)

```
use GoldenPathDigital\Claude\Facades\Claude;

$response = Claude::conversation()
    ->model('claude-sonnet-4-5-20250929')
    ->system('You are a helpful assistant.')
    ->user('What is the capital of France?')
    ->maxTokens(1024)
    ->temperature(0.7)
    ->send();

echo $response->content[0]->text;
```

### Multi-turn Conversations

[](#multi-turn-conversations)

```
$conversation = Claude::conversation()
    ->system('You are a code reviewer.')
    ->user('Review this function: function add($a, $b) { return $a + $b; }')
    ->send();

// Continue the conversation
$followUp = $conversation
    ->user('What about error handling?')
    ->send();
```

### Image Support

[](#image-support)

Send images for Claude to analyze:

```
use GoldenPathDigital\Claude\Facades\Claude;

// Base64 encoded image
$imageData = base64_encode(file_get_contents('photo.jpg'));

$response = Claude::conversation()
    ->image($imageData, 'image/jpeg', 'What is in this image?')
    ->send();

// URL-based image
$response = Claude::conversation()
    ->imageUrl('https://example.com/image.png', 'Describe this diagram')
    ->send();

// Complex multi-modal messages
$response = Claude::conversation()
    ->user([
        ['type' => 'text', 'text' => 'Compare these two images:'],
        ['type' => 'image', 'source' => ['type' => 'url', 'url' => 'https://example.com/img1.jpg']],
        ['type' => 'image', 'source' => ['type' => 'url', 'url' => 'https://example.com/img2.jpg']],
    ])
    ->send();
```

### PDF Documents

[](#pdf-documents)

Analyze PDF documents:

```
use GoldenPathDigital\Claude\Facades\Claude;

$pdfData = base64_encode(file_get_contents('contract.pdf'));

$response = Claude::conversation()
    ->pdf($pdfData, 'Extract the key terms from this contract')
    ->send();
```

### Advanced Parameters

[](#advanced-parameters)

Fine-tune model behavior with additional parameters:

```
use GoldenPathDigital\Claude\Facades\Claude;

$response = Claude::conversation()
    ->model('claude-sonnet-4-5-20250929')
    ->system('You are a helpful assistant.')
    ->user('Write a haiku about coding.')
    ->maxTokens(1024)
    ->temperature(0.7)
    ->topK(40)                          // Limit token selection pool
    ->topP(0.9)                         // Nucleus sampling threshold
    ->stopSequences(['END', '---'])     // Custom stop sequences
    ->metadata(['user_id' => 'user_123']) // Usage tracking
    ->serviceTier('auto')               // 'auto' or 'standard_only'
    ->send();
```

### Streaming

[](#streaming)

Stream responses in real-time with callback support:

```
use GoldenPathDigital\Claude\Facades\Claude;

Claude::conversation()
    ->system('You are a helpful assistant.')
    ->user('Write a short poem about Laravel.')
    ->stream(function (string $text) {
        echo $text; // Output each chunk as it arrives
    });
```

Or listen for Laravel events:

```
use GoldenPathDigital\Claude\Events\StreamChunk;
use GoldenPathDigital\Claude\Events\StreamComplete;

Event::listen(StreamChunk::class, function (StreamChunk $event) {
    broadcast(new NewChunk($event->text)); // Real-time to frontend
});

Event::listen(StreamComplete::class, function (StreamComplete $event) {
    logger()->info('Stream complete', [
        'input_tokens' => $event->usage['input_tokens'],
        'output_tokens' => $event->usage['output_tokens'],
    ]);
});
```

### Tools

[](#tools)

Define tools with a fluent builder and let Claude execute them automatically:

```
use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\Tools\Tool;

$weatherTool = Tool::make('get_weather')
    ->description('Get the current weather for a location')
    ->parameter('location', 'string', 'City name', required: true)
    ->parameter('units', 'string', 'Temperature units', enum: ['celsius', 'fahrenheit'])
    ->handler(function (array $input) {
        // Call your weather API here
        return ['temperature' => 72, 'condition' => 'sunny'];
    });

$response = Claude::conversation()
    ->system('You are a helpful assistant with access to weather data.')
    ->user('What is the weather in Paris?')
    ->tools([$weatherTool])
    ->maxSteps(5) // Maximum tool execution iterations
    ->send();

echo $response->content[0]->text;
// "The current weather in Paris is 72 degrees and sunny."
```

### MCP Connector

[](#mcp-connector)

Connect to remote [MCP servers](https://modelcontextprotocol.io/) via Anthropic's connector API:

```
use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\MCP\McpServer;

// Define MCP server inline
$zapier = McpServer::url('https://mcp.zapier.com/api/mcp/s/xxx')
    ->name('zapier')
    ->token(env('ZAPIER_MCP_TOKEN'))
    ->allowTools(['gmail_send', 'slack_post']); // Optional: restrict tools

$response = Claude::conversation()
    ->system('You are an assistant that can send emails and Slack messages.')
    ->user('Send a Slack message to #general saying hello')
    ->mcp([$zapier])
    ->send();
```

Or use pre-configured servers from config:

```
// config/claude.php
'mcp_servers' => [
    'zapier' => [
        'url' => env('ZAPIER_MCP_URL'),
        'token' => env('ZAPIER_MCP_TOKEN'),
        'allowed_tools' => ['gmail_send', 'slack_post'],
    ],
],

// Usage - reference by config key
$response = Claude::conversation()
    ->mcp(['zapier']) // Loads from config
    ->user('Send an email to john@example.com')
    ->send();
```

### Extended Thinking

[](#extended-thinking)

Enable Claude's reasoning process for complex problems:

```
use GoldenPathDigital\Claude\Facades\Claude;

$response = Claude::conversation()
    ->model('claude-sonnet-4-5-20250929')
    ->extendedThinking(budgetTokens: 10000)
    ->user('Analyze the pros and cons of microservices vs monolith architecture.')
    ->send();

// Access thinking blocks in response
foreach ($response->content as $block) {
    if ($block->type === 'thinking') {
        logger()->info('Claude reasoning:', ['thinking' => $block->thinking]);
    }
    if ($block->type === 'text') {
        echo $block->text;
    }
}
```

### Prompt Caching

[](#prompt-caching)

Reduce costs by caching large system prompts:

```
use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\ValueObjects\CachedContent;

// Cache a long system prompt
$systemPrompt = CachedContent::make($longDocumentation)
    ->cache('ephemeral');

$response = Claude::conversation()
    ->system($systemPrompt)
    ->user('Summarize the key points.')
    ->send();

// Check cache usage in response
// $response->usage->cache_creation_input_tokens
// $response->usage->cache_read_input_tokens
```

### Structured Outputs

[](#structured-outputs)

Get responses validated against a JSON schema:

```
use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\Conversation\ConversationBuilder;

$schema = [
    'type' => 'object',
    'properties' => [
        'parties' => ['type' => 'array', 'items' => ['type' => 'string']],
        'effective_date' => ['type' => 'string'],
        'term_length' => ['type' => 'string'],
        'key_obligations' => ['type' => 'array', 'items' => ['type' => 'string']],
    ],
    'required' => ['parties', 'effective_date'],
];

$response = Claude::conversation()
    ->user('Extract the key terms from this contract: ...')
    ->schema($schema, 'contract_terms')
    ->send();

// Extract structured data from the tool_use response
$data = ConversationBuilder::extractStructuredOutput($response);

echo $data['parties'][0]; // "Acme Corp"
echo $data['effective_date']; // "2025-01-01"
```

Testing
-------

[](#testing)

Use `Claude::fake()` to mock responses in your tests:

```
use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\Testing\FakeResponse;

public function test_chatbot_responds()
{
    Claude::fake([
        FakeResponse::make('Hello! How can I help you today?'),
    ]);

    $response = Claude::conversation()
        ->user('Hi there!')
        ->send();

    $this->assertEquals('Hello! How can I help you today?', $response->content[0]->text);

    // Assert the request was sent
    Claude::assertSent(function (array $request) {
        return $request['messages'][0]['content'] === 'Hi there!';
    });
}
```

### Available Assertions

[](#available-assertions)

```
// Assert any request was sent
Claude::assertSent();

// Assert with callback
Claude::assertSent(function (array $request) {
    return str_contains($request['messages'][0]['content'], 'hello');
});

// Assert nothing was sent
Claude::assertNothingSent();

// Assert specific count
Claude::assertSentCount(3);
```

### Faking Tool Use Responses

[](#faking-tool-use-responses)

```
Claude::fake([
    FakeResponse::withToolUse('get_weather', ['location' => 'Paris']),
    FakeResponse::make('The weather in Paris is sunny and 72 degrees.'),
]);
```

Configuration
-------------

[](#configuration)

```
// config/claude.php

return [
    // Authentication
    'api_key' => env('ANTHROPIC_API_KEY'),
    'auth_token' => env('ANTHROPIC_AUTH_TOKEN'),  // Alternative OAuth authentication

    // Custom endpoint (for proxies or enterprise)
    'base_url' => env('ANTHROPIC_BASE_URL'),

    // Defaults
    'default_model' => env('CLAUDE_MODEL', 'claude-sonnet-4-5-20250929'),
    'timeout' => env('CLAUDE_TIMEOUT', 30),
    'max_retries' => 2,

    // Beta features (auto-enabled headers)
    'beta_features' => [
        'mcp_connector' => true,
        'extended_thinking' => true,
        'prompt_caching' => true,
        'structured_outputs' => true,
    ],

    // Pre-configured MCP servers
    'mcp_servers' => [
        'zapier' => [
            'url' => env('ZAPIER_MCP_URL'),
            'token' => env('ZAPIER_MCP_TOKEN'),
        ],
    ],

    // Pricing per million tokens (for cost estimation)
    'pricing' => [
        'claude-opus' => ['input' => 15.00, 'output' => 75.00],
        'claude-sonnet' => ['input' => 3.00, 'output' => 15.00],
        'claude-haiku' => ['input' => 0.25, 'output' => 1.25],
    ],
];
```

### Queue Integration

[](#queue-integration)

Process conversations in background jobs with automatic retry handling:

```
use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\Jobs\ProcessConversation;
use GoldenPathDigital\Claude\Contracts\ConversationCallback;
use Anthropic\Messages\Message;
use Throwable;

// Create a callback to handle the result
class DocumentAnalysisCallback implements ConversationCallback
{
    public function onSuccess(Message $response, array $context = []): void
    {
        $document = Document::find($context['document_id']);
        $document->update([
            'summary' => $response->content[0]->text,
            'analyzed_at' => now(),
        ]);
    }

    public function onFailure(Throwable $exception, array $context = []): void
    {
        Log::error('Document analysis failed', [
            'document_id' => $context['document_id'],
            'error' => $exception->getMessage(),
        ]);
    }
}

// Dispatch the conversation to the queue
ProcessConversation::dispatch(
    conversation: Claude::conversation()
        ->system('You are a document analyst. Summarize the key points.')
        ->user($documentContent),
    callbackClass: DocumentAnalysisCallback::class,
    context: ['document_id' => $document->id]
)->onQueue('ai');
```

The job includes:

- **Automatic retries**: 3 attempts with 10 second backoff
- **Callback pattern**: Handle success/failure in dedicated classes
- **Context passing**: Pass arbitrary data to the callback
- **Full feature support**: MCP servers, extended thinking, caching, structured outputs

**Note**: Tools with custom handlers (closures) cannot be serialized for queue jobs. Use MCP servers or basic conversations for queued processing.

Running Tests
-------------

[](#running-tests)

```
composer test
```

Code Style
----------

[](#code-style)

```
composer format
```

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance76

Regular maintenance activity

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

6

Last Release

133d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0db315144227366ae7acd8456a92e195e198e7c465efb2f047478767e17e6e62?d=identicon)[goldenpathdigital](/maintainers/goldenpathdigital)

---

Top Contributors

[![aarongrtech](https://avatars.githubusercontent.com/u/123791395?v=4)](https://github.com/aarongrtech "aarongrtech (31 commits)")

---

Tags

laravelsdkmcpaiclaudellmanthropic

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/goldenpathdigital-laravel-claude/health.svg)

```
[![Health](https://phpackages.com/badges/goldenpathdigital-laravel-claude/health.svg)](https://phpackages.com/packages/goldenpathdigital-laravel-claude)
```

###  Alternatives

[claude-php/claude-php-sdk-laravel

Laravel integration for the Claude PHP SDK - Anthropic Claude API

5010.8k](/packages/claude-php-claude-php-sdk-laravel)[vizra/vizra-adk

Vizra Agent Development Kit - A comprehensive Laravel package for building intelligent AI agents.

29026.1k](/packages/vizra-vizra-adk)[neuron-core/neuron-laravel

Official Neuron AI Laravel SDK.

10710.0k](/packages/neuron-core-neuron-laravel)[mozex/anthropic-laravel

Anthropic PHP for Laravel is a supercharged PHP API client that allows you to interact with the Anthropic API

71226.4k1](/packages/mozex-anthropic-laravel)[sbsaga/toon

🧠 TOON for Laravel — a compact, human-readable, and token-efficient data format for AI prompts &amp; LLM contexts. Perfect for ChatGPT, Gemini, Claude, Mistral, and OpenAI integrations (JSON ⇄ TOON).

6115.6k](/packages/sbsaga-toon)[cboxdk/statamic-mcp

MCP (Model Context Protocol) server for Statamic CMS v6 — gives AI assistants structured access to content, blueprints, assets, and more.

225.6k](/packages/cboxdk-statamic-mcp)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
