PHP code example of goldenpathdigital / laravel-claude
1. Go to this page and download the library: Download goldenpathdigital/laravel-claude library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
goldenpathdigital / laravel-claude example snippets
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;
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, []);
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;
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)
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;
$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();
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();
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();
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
});
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'],
]);
});
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', $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."
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();
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;
}
}
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
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!';
});
}
// 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);
Claude::fake([
FakeResponse::withToolUse('get_weather', ['location' => 'Paris']),
FakeResponse::make('The weather in Paris is sunny and 72 degrees.'),
]);
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');