Integrating an AI API in Laravel

By Darus S Alfatah · 2025-09-13 · Tutorial · 8 menit

Integrating an AI API in Laravel

Author note: Keep keys in .env and never put them in code that enters the repository.

Focus of this article

This article is Laravel-specific: HTTP client, service configuration, and response handling. For framework-free PHP, see the companion article.

Read also: Calling an AI API From PHP With cURL

Keep Controllers Thin

A controller should validate input and return a response, nothing more. Put model calls in a dedicated service class so retries, logging, and configuration live in one place. This structure makes testing straightforward and future provider changes cheap.

Inject the service rather than resolving it inline; tests can then substitute a fake without touching HTTP.

Use the HTTP Client

Laravel's HTTP client handles retries, timeouts, and error responses with little code. Configure the base URL and token once, and reuse the client everywhere.

Set a timeout that reflects user patience, and a retry policy that does not multiply cost. Two attempts with a short delay covers most transient failures.

Configuration and Secrets

Read keys from environment variables through config files, then cache the config in production. Never commit the key, and rotate it if it appears in logs.

Use separate keys for local development and production so a test loop cannot exhaust production quota.

Queues for Heavy Work

Document summarisation, bulk classification, and report generation belong in a queue. The request returns immediately, and the job handles retries with backoff while the user receives a notification when it finishes.

Set the job timeout higher than the HTTP timeout, otherwise the job is killed while the request is still running.

Caching

Cache answers for repeated questions with a short lifetime. For support applications, this can halve the bill without any change to prompts.

Key the cache by prompt plus relevant context, not by prompt alone, otherwise different contexts collide.

Testing

Fake HTTP responses in tests: one success, one error, one malformed body. Assert that your code handles each gracefully. Integration tests against the real API should run manually before release, with a small budget.

Frequently Asked Questions

Where should prompts live? In a config or a dedicated class, not scattered in controllers.

How do I log usage? Store tokens and feature names in a table for monthly reporting.

Can I stream from Laravel? Yes, with a streamed response.

What about multi-tenant apps? Track usage per tenant from the start.

How do I handle timeouts? Return a friendly message and log the failure.

Conclusion

Laravel gives you the pieces: service classes, HTTP client, queues, and cache. Combining them well turns an integration into maintainable infrastructure.

Operational Practices

Log tokens, latency, and status per feature, and review the numbers weekly during the first month. Add alerts for error-rate spikes so problems surface before customers report them.

Document the prompts in the repository with a note on why each rule exists. Future maintainers will otherwise delete rules that look redundant but prevent a specific failure.

Finally, isolate AI features behind a simple feature flag so they can be disabled quickly if a provider degrades. A flag costs minutes to add and can save an afternoon of incident response.

Keep an eye on queue depth as well. A backlog means jobs are slower than they arrive, and users experience delayed results even though the interface responded instantly.

Review retention weekly until the numbers are predictable, then monthly.

An example of safe config: Store the key in config/services.php from .env, call it via a service class, and never place it in blades or JavaScript.

Frequently Asked Questions

Can beginners follow this tutorial?

Yes. The steps are explained in order with code examples, suitable for beginners and experienced developers alike.

Is BankAI’s endpoint compatible with the library I already use?

Yes, BankAI is 100% OpenAI-compatible, so libraries such as the OpenAI SDK and LangChain work without code changes beyond the Base URL and API key.

Where do I get an API key to follow this tutorial?

You get the API key (and Secret Token) after registering and completing payment in the BankAI dashboard.

Sources & References

About the author

Darus S Alfatah — Founder & Writer

Darus S Alfatah is the founder of BankAI. He builds and operates the LLM API gateway that serves Indonesian developers, and writes about LLM integration, gateway architecture, and using AI practically and cost-effectively. Every guide is tested in a real environment — including code, configuration, and token calculations — before it is published, and updated when provider documentation or pricing changes.

Editorial policy

Related articles

🚀 Ready to Use the All-in-One API Key?

Sign up, top up with QRIS, and start building with ChatGPT, Claude, DeepSeek and every other model through one key.

🔑 SIGN UP NOW · Pricing