Adding AI capabilities to Laravel apps is straightforward when you separate concerns: API calls in services, responses via resources, and heavy work in queued jobs.
Setup
Install the official OpenAI PHP client and store your API key in .env — never commit secrets to version control.
OPENAI_API_KEY=sk-...
OPENAI_ORGANIZATION=org-...
Service Layer Pattern
Wrap API calls in a dedicated AiService class. Inject it into controllers so you can mock it in tests and swap providers later.
Streaming Responses
For chat UIs, stream tokens with Laravel's streamed responses so users see output progressively instead of waiting for the full completion.
Queue Long Requests
Summarization, embeddings, and batch processing belong in queued jobs with retries and rate-limit handling — keeping HTTP requests fast.
Security Checklist
- Validate and sanitize all user prompts server-side.
- Apply per-user rate limits to control costs.
- Log token usage for billing visibility.