Integrating AI Into Laravel

Most AI tutorials assume you use Python.

After 12 years of building PHP apps, I recently added AI features to a production Laravel dashboard. I used it to turn raw data into human reports.

The hard part was not the code. The hard part was finding good PHP content on this topic.

Here is how you build a clean, production-ready AI integration in Laravel.

The Architecture

Do not scatter API calls inside your controllers. Instead, use a driver pattern. This lets you switch between Claude and OpenAI with one change in your .env file.

  1. Define a contract Create an AiClientInterface. This ensures both Claude and OpenAI follow the same rules.

  2. Build your drivers Create a ClaudeClient and an OpenAiClient. Use Laravel's HTTP client to handle the requests. It makes handling timeouts and retries easy.

  3. Use the Service Container Bind your interface to a specific client in your AppServiceProvider. Use a match statement to choose the provider based on your config.

The Differences

You must know these five details to avoid errors:

• Claude uses x-api-key in the header. OpenAI uses Authorization: Bearer. • Claude requires an anthropic-version header. • Claude requires max_tokens. OpenAI makes it optional. • Claude uses a top-level system field. OpenAI uses a message with the role: system. • The JSON response paths differ. Claude uses content[0].text. OpenAI uses choices[0].message.content.

Production Tips

• Use Caching: AI calls are slow and cost money. If the data is the same, serve the result from your cache. This can cut costs by 70%. • Use Queues: Never make a user wait 10 seconds for an API response. Dispatch a background job and notify them when it is ready. • Handle Failures: APIs fail. Wrap your calls in try-catch blocks. If the AI fails, show the raw data instead of a broken page. • Set Limits: Always set max_tokens to control your spending. Use smaller, cheaper models for simple tasks like summaries.

You do not need to learn Python to build AI features. Your PHP skills work perfectly here.

Source: https://dev.to/sunakshi_thakur_84a5f59fd/integrating-claudeopenai-api-into-a-laravel-app-a-practical-guide-1hig