{"id":317,"date":"2026-11-05T17:00:00","date_gmt":"2026-11-05T12:00:00","guid":{"rendered":"https:\/\/www.shaz3e.com\/blog\/?p=317"},"modified":"2026-11-08T17:20:36","modified_gmt":"2026-11-08T12:20:36","slug":"laravel-llm-api","status":"publish","type":"post","link":"https:\/\/www.shaz3e.com\/blog\/laravel-llm-api\/","title":{"rendered":"Calling LLM APIs from Laravel: Queues, Streaming and Costs"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">A Laravel OpenAI integration looks like one HTTP call, and in a demo it is. In production that call takes several seconds, sometimes fails with a 429, and costs money every time it runs. If it sits inside a controller, your users wait on it, your PHP workers pile up behind it, and nobody can tell you next month which feature ran up the bill.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This guide covers the three things I set up before any LLM feature ships: queued calls for work the user doesn&#8217;t need to watch, streaming for work they do, and a usage table that records tokens and cost per feature. It uses Laravel&#8217;s own HTTP client, so there&#8217;s no SDK to learn, and the same code works with any provider that speaks the OpenAI chat completions format.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"contents\">What this post covers<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n\n<li><a href=\"#versions\">Tested versions<\/a><\/li>\n\n\n<li><a href=\"#client\">A small LLM client on Laravel&#8217;s HTTP client<\/a><\/li>\n\n\n<li><a href=\"#queue\">Queued calls for background work<\/a><\/li>\n\n\n<li><a href=\"#stream\">Streaming responses to the browser<\/a><\/li>\n\n\n<li><a href=\"#costs\">Tracking tokens and cost per feature<\/a><\/li>\n\n\n<li><a href=\"#tests\">Testing it without spending a cent<\/a><\/li>\n\n\n<li><a href=\"#faq\">FAQ<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"versions\">Tested versions<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Tool<\/th><th>Version<\/th><\/tr><\/thead><tbody><tr><td>Laravel Framework<\/td><td>13.40.0 (fresh <code>laravel\/laravel<\/code> skeleton)<\/td><\/tr><tr><td>PHP<\/td><td>8.4.27 CLI<\/td><\/tr><tr><td>Composer<\/td><td>2.8.8<\/td><\/tr><tr><td>Database<\/td><td>SQLite (the skeleton default)<\/td><\/tr><tr><td>Tests<\/td><td>PHPUnit through <code>php artisan test<\/code>, 6 tests passing<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Every code block below comes from that app. The tests fake the API, so nothing here was checked against a live account&#8217;s rate limits or prices. Treat model names and price numbers as placeholders and copy the real ones from your provider.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"client\">A small LLM client on Laravel&#8217;s HTTP client<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Start with config. The key lives in <code>.env<\/code>, and so do the prices, because they change and you don&#8217;t want a deploy every time they do.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>'openai' =&gt; [\n    'key' =&gt; env('OPENAI_API_KEY'),\n    'url' =&gt; env('OPENAI_URL', 'https:\/\/api.openai.com\/v1'),\n    'model' =&gt; env('OPENAI_MODEL', 'gpt-4o-mini'),\n    'timeout' =&gt; (int) env('OPENAI_TIMEOUT', 60),\n    \/\/ Prices per 1M tokens, copied from your provider's pricing page.\n    'price_in' =&gt; (float) env('OPENAI_PRICE_INPUT', 0),\n    'price_out' =&gt; (float) env('OPENAI_PRICE_OUTPUT', 0),\n],<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then one class that every feature goes through. Keeping it to one class matters more than it looks: it&#8217;s the only place that knows the URL, the timeout and the response shape, and it&#8217;s where usage gets recorded, so no feature can skip it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>namespace App\\Services\\Llm;\n\nuse App\\Models\\LlmUsage;\nuse Illuminate\\Http\\Client\\PendingRequest;\nuse Illuminate\\Support\\Facades\\Http;\n\nclass LlmClient\n{\n    private function http(): PendingRequest\n    {\n        return Http::baseUrl(config('services.openai.url'))\n            -&gt;withToken(config('services.openai.key'))\n            -&gt;timeout(config('services.openai.timeout'))\n            -&gt;acceptJson();\n    }\n\n    \/** One request, one full answer. Use this inside queued jobs. *\/\n    public function chat(array $messages, string $feature, ?int $maxTokens = 500): string\n    {\n        $response = $this-&gt;http()\n            -&gt;post('\/chat\/completions', [\n                'model' =&gt; config('services.openai.model'),\n                'messages' =&gt; $messages,\n                'max_tokens' =&gt; $maxTokens,\n            ])\n            -&gt;throw();\n\n        $this-&gt;recordUsage($feature, $response-&gt;json('model'), $response-&gt;json('usage', []));\n\n        return (string) $response-&gt;json('choices.0.message.content');\n    }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Two details. <code>->throw()<\/code> turns any 4xx or 5xx into a <code>RequestException<\/code>, which the queued job below uses to decide whether to retry. And the timeout is set on purpose: the default can leave a worker hanging on a slow model far longer than you&#8217;d want. If you haven&#8217;t set retries and timeouts on outbound calls before, <a href=\"https:\/\/www.shaz3e.com\/blog\/laravel-http-client-retry\/\">building resilient HTTP clients in Laravel<\/a> goes deeper on that.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"queue\">Queued calls for background work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Most LLM work doesn&#8217;t need to happen while the user waits. Summarizing a ticket, tagging a lead, drafting a reply someone will review later: all of that belongs in a job. The request saves the record and returns in milliseconds, and a worker makes the slow call.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>namespace App\\Jobs;\n\nuse App\\Models\\TicketSummary;\nuse App\\Services\\Llm\\LlmClient;\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\nuse Illuminate\\Foundation\\Queue\\Queueable;\nuse Illuminate\\Http\\Client\\RequestException;\nuse Illuminate\\Queue\\Middleware\\RateLimited;\n\nclass SummarizeTicket implements ShouldQueue\n{\n    use Queueable;\n\n    public int $maxExceptions = 3;\n    public int $timeout = 90;\n\n    public function __construct(public TicketSummary $ticket) {}\n\n    \/** Keep trying for 10 minutes; rate-limit releases don't count as failures. *\/\n    public function retryUntil(): \\DateTime\n    {\n        return now()-&gt;addMinutes(10);\n    }\n\n    \/** Wait longer between each failed attempt: 10s, 30s, then 90s. *\/\n    public function backoff(): array\n    {\n        return [10, 30, 90];\n    }\n\n    public function middleware(): array\n    {\n        return [new RateLimited('llm')];\n    }\n\n    public function handle(LlmClient $llm): void\n    {\n        if ($this-&gt;ticket-&gt;summary !== null) {\n            return; \/\/ Already done on an earlier attempt.\n        }\n\n        try {\n            $summary = $llm-&gt;chat([\n                ['role' =&gt; 'system', 'content' =&gt; 'Summarize the support ticket in two sentences.'],\n                ['role' =&gt; 'user', 'content' =&gt; $this-&gt;ticket-&gt;body],\n            ], feature: 'ticket-summary', maxTokens: 120);\n        } catch (RequestException $e) {\n            \/\/ 400, 401 and 404 will fail the same way every time. Don't retry them.\n            if (in_array($e-&gt;response-&gt;status(), [400, 401, 403, 404], true)) {\n                $this-&gt;fail($e);\n\n                return;\n            }\n\n            throw $e; \/\/ 429 and 5xx: let the queue retry with backoff.\n        }\n\n        $this-&gt;ticket-&gt;update(['summary' =&gt; $summary]);\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A few choices here are deliberate:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n\n<li><strong>Not every error deserves a retry.<\/strong> A 429 or a 500 usually clears up, so the job rethrows and the queue tries again after the backoff. A 400 or 401 means the request or the key is wrong, and retrying just burns attempts, so the job fails straight away.<\/li>\n\n\n<li><strong>Rate limiting at the job level.<\/strong> The <code>RateLimited<\/code> middleware uses a limiter defined once in <code>AppServiceProvider<\/code> with <code>RateLimiter::for('llm', fn ($job) => Limit::perMinute(60))<\/code>. Set the number to whatever your provider allows. The <a href=\"https:\/\/laravel.com\/docs\/13.x\/queues\" target=\"_blank\" rel=\"noopener\">Laravel queue docs<\/a> point out that a rate-limited release counts as an attempt, which is why the job uses <code>retryUntil()<\/code> and <code>$maxExceptions<\/code> instead of a fixed <code>$tries<\/code>. Otherwise a busy minute could use up every try without a single real failure.<\/li>\n\n\n<li><strong>The early return makes retries safe.<\/strong> If an earlier attempt already saved a summary, a retry doesn&#8217;t pay for a second one.<\/li>\n\n\n<li><strong><code>max_tokens<\/code> is set per feature.<\/strong> A two-sentence summary doesn&#8217;t need 500 tokens of room. Capping output is the simplest cost control there is.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Dispatching is one line from wherever the ticket gets created:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ticket = TicketSummary::create(['body' =&gt; $request-&gt;input('body')]);\n\nSummarizeTicket::dispatch($ticket);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Give these jobs their own queue if they run alongside time-sensitive work like password-reset emails, so a burst of AI jobs can&#8217;t delay everything else. <a href=\"https:\/\/www.shaz3e.com\/blog\/laravel-queue-workers\/\">Laravel queue workers in production<\/a> covers Supervisor, separate queues and scaling workers.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"stream\">Streaming responses to the browser<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Some answers the user is waiting for: a chat reply, an explanation they asked for. Queuing those doesn&#8217;t help, because they&#8217;d just poll for the result. Streaming does. The first words show up as soon as the model produces them, and the wait feels far shorter even though the total time is the same.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Pass <code>'stream' => true<\/code> in the request body so the API sends server-sent events, and <code>['stream' => true]<\/code> as a Guzzle option so Laravel doesn&#8217;t wait for the whole body before handing it to you. Then read the body in pieces and pull the text out of each event:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/** Streams the answer, yielding text chunks as they arrive. *\/\npublic function stream(array $messages, string $feature, ?int $maxTokens = 500): \\Generator\n{\n    $response = $this-&gt;http()\n        -&gt;withOptions(['stream' =&gt; true])\n        -&gt;post('\/chat\/completions', [\n            'model' =&gt; config('services.openai.model'),\n            'messages' =&gt; $messages,\n            'max_tokens' =&gt; $maxTokens,\n            'stream' =&gt; true,\n            'stream_options' =&gt; ['include_usage' =&gt; true],\n        ])\n        -&gt;throw();\n\n    $body = $response-&gt;toPsrResponse()-&gt;getBody();\n    $buffer = '';\n\n    while (! $body-&gt;eof()) {\n        $buffer .= $body-&gt;read(1024);\n\n        \/\/ Server-sent events are separated by a blank line.\n        while (($pos = strpos($buffer, \"\\n\\n\")) !== false) {\n            $event = substr($buffer, 0, $pos);\n            $buffer = substr($buffer, $pos + 2);\n\n            foreach (explode(\"\\n\", $event) as $line) {\n                if (! str_starts_with($line, 'data: ')) {\n                    continue;\n                }\n\n                $data = substr($line, 6);\n\n                if ($data === '[DONE]') {\n                    return;\n                }\n\n                $chunk = json_decode($data, true);\n\n                if (! empty($chunk['usage'])) {\n                    $this-&gt;recordUsage($feature, $chunk['model'] ?? null, $chunk['usage']);\n                }\n\n                $text = $chunk['choices'][0]['delta']['content'] ?? '';\n\n                if ($text !== '') {\n                    yield $text;\n                }\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The buffer is there because a network read can end halfway through an event. The loop only parses up to the last blank line and keeps the rest for the next read. <code>stream_options.include_usage<\/code> asks the API to send token counts in a final event, which is how streamed calls still get recorded.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Laravel 13 has <code>response()->eventStream()<\/code> for the other half, sending events on to the browser. It&#8217;s covered in the <a href=\"https:\/\/laravel.com\/docs\/13.x\/responses\" target=\"_blank\" rel=\"noopener\">Laravel responses docs<\/a>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Route::get('\/ai\/explain', function (\\Illuminate\\Http\\Request $request, \\App\\Services\\Llm\\LlmClient $llm) {\n    $question = $request-&gt;string('q')-&gt;limit(500)-&gt;toString();\n\n    return response()-&gt;eventStream(function () use ($llm, $question) {\n        foreach ($llm-&gt;stream([\n            ['role' =&gt; 'user', 'content' =&gt; $question],\n        ], feature: 'explain') as $text) {\n            yield $text;\n        }\n    });\n})-&gt;middleware('throttle:10,1');<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s what the browser actually receives for a short two-chunk answer, captured from the test app:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>event: update\ndata: Queues \n\nevent: update\ndata: keep requests fast.\n\nevent: update\ndata: &lt;\/stream&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">On the front end, a plain <code>EventSource<\/code> listening for <code>update<\/code> events works, and you close it when <code>&lt;\/stream&gt;<\/code> arrives. If your UI is React or Next.js, <a href=\"https:\/\/www.shaz3e.com\/blog\/nextjs-streaming-ai-responses\/\">streaming AI responses in a Next.js UI<\/a> shows the rendering side, including what to do when the user navigates away mid-answer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Two warnings for this route. Every open stream holds a PHP worker for as long as it runs, so the <code>throttle<\/code> middleware isn&#8217;t optional on a public endpoint. And some proxies and hosts buffer responses, which turns a stream back into one slow response. If chunks arrive all at once in production but not locally, check the proxy before blaming the code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"costs\">Tracking tokens and cost per feature<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Every response, streamed or not, includes a <code>usage<\/code> block with prompt and completion tokens. The client writes one row per call:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Schema::create('llm_usages', function (Blueprint $table) {\n    $table-&gt;id();\n    $table-&gt;string('feature')-&gt;index();\n    $table-&gt;string('model');\n    $table-&gt;unsignedInteger('input_tokens');\n    $table-&gt;unsignedInteger('output_tokens');\n    $table-&gt;decimal('cost', 12, 6);\n    $table-&gt;timestamps();\n});<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>private function recordUsage(string $feature, ?string $model, array $usage): void\n{\n    $in = (int) ($usage['prompt_tokens'] ?? 0);\n    $out = (int) ($usage['completion_tokens'] ?? 0);\n\n    LlmUsage::create([\n        'feature' =&gt; $feature,\n        'model' =&gt; $model ?? config('services.openai.model'),\n        'input_tokens' =&gt; $in,\n        'output_tokens' =&gt; $out,\n        'cost' =&gt; ($in * config('services.openai.price_in')\n            + $out * config('services.openai.price_out')) \/ 1_000_000,\n    ]);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>feature<\/code> column is the part that pays off. The provider&#8217;s dashboard tells you what you spent. This table tells you that ticket summaries cost a little and the explain button costs far more because people paste whole documents into it. That&#8217;s the question you&#8217;ll actually get asked. Monthly spend per feature is one query:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>LlmUsage::selectRaw('feature, sum(input_tokens) as input, sum(output_tokens) as output, sum(cost) as cost')\n    -&gt;where('created_at', '&gt;=', now()-&gt;startOfMonth())\n    -&gt;groupBy('feature')\n    -&gt;orderByDesc('cost')\n    -&gt;get();<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The stored cost is an estimate built from the prices in your config, so keep those current. Cached input, batch discounts and different prices per model all make the real invoice differ a bit. It&#8217;s close enough to spot which feature is growing, which is what you need it for.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you&#8217;re deciding which features deserve an LLM in the first place, my guide to <a href=\"https:\/\/www.shaz3e.com\/blog\/ai-assisted-software-development\/\">using AI in software development responsibly<\/a> covers the review and data questions, and Diligent Creators has a plain-language overview of <a href=\"https:\/\/diligentcreators.com\/blog\/how-to-add-ai-features-to-your-web-app-using-openai-apis\/\" target=\"_blank\" rel=\"noopener\">adding AI features to a web app with OpenAI APIs<\/a> that&#8217;s handy for the non-developers in the room.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"tests\">Testing it without spending a cent<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Because everything goes through Laravel&#8217;s HTTP client, <code>Http::fake()<\/code> covers it. No API key, no network, no bill. Here&#8217;s the job test, which also checks the cost maths with example prices of 0.15 and 0.60 per million tokens (made-up numbers for the test, not anyone&#8217;s real pricing):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function test_job_saves_summary_and_records_usage(): void\n{\n    Http::fake([\n        'api.openai.com\/*' =&gt; Http::response([\n            'model' =&gt; 'gpt-4o-mini',\n            'choices' =&gt; [['message' =&gt; ['content' =&gt; 'Customer was billed the wrong amount.']]],\n            'usage' =&gt; ['prompt_tokens' =&gt; 1200, 'completion_tokens' =&gt; 300],\n        ]),\n    ]);\n    $ticket = TicketSummary::create(['body' =&gt; 'My invoice shows the wrong amount.']);\n\n    SummarizeTicket::dispatchSync($ticket);\n\n    $this-&gt;assertSame('Customer was billed the wrong amount.', $ticket-&gt;fresh()-&gt;summary);\n    $usage = LlmUsage::sole();\n    $this-&gt;assertSame('ticket-summary', $usage-&gt;feature);\n    $this-&gt;assertSame(1200, $usage-&gt;input_tokens);\n    \/\/ (1200 * 0.15 + 300 * 0.60) \/ 1,000,000\n    $this-&gt;assertEqualsWithDelta(0.00036, (float) $usage-&gt;cost, 0.0000001);\n    Http::assertSent(fn ($r) =&gt; $r-&gt;hasHeader('Authorization', 'Bearer test-key')\n        &amp;&amp; $r['max_tokens'] === 120);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Streaming can be faked the same way. Hand the fake a string of server-sent events and the client reads it like a real stream:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function test_stream_yields_chunks_and_records_usage(): void\n{\n    $sse = implode('', [\n        \"data: {\\\"choices\\\":[{\\\"delta\\\":{\\\"content\\\":\\\"Queues \\\"}}]}\\n\\n\",\n        \"data: {\\\"choices\\\":[{\\\"delta\\\":{\\\"content\\\":\\\"keep requests fast.\\\"}}]}\\n\\n\",\n        \"data: {\\\"model\\\":\\\"gpt-4o-mini\\\",\\\"choices\\\":[],\\\"usage\\\":{\\\"prompt_tokens\\\":20,\\\"completion_tokens\\\":5}}\\n\\n\",\n        \"data: [DONE]\\n\\n\",\n    ]);\n    Http::fake(['api.openai.com\/*' =&gt; Http::response($sse, 200, ['Content-Type' =&gt; 'text\/event-stream'])]);\n\n    $chunks = iterator_to_array(app(LlmClient::class)-&gt;stream(\n        [['role' =&gt; 'user', 'content' =&gt; 'Why queues?']], 'explain'), false);\n\n    $this-&gt;assertSame(['Queues ', 'keep requests fast.'], $chunks);\n    $this-&gt;assertSame(5, LlmUsage::sole()-&gt;output_tokens);\n    Http::assertSent(fn ($r) =&gt; $r['stream'] === true\n        &amp;&amp; $r['stream_options'] === ['include_usage' =&gt; true]);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The full test file also checks that a 400 fails the job without a retry and that a 429 is rethrown so the queue retries it. All six pass on the versions above. For more on faking external APIs, including sequences and asserting on requests, see <a href=\"https:\/\/www.shaz3e.com\/blog\/laravel-http-fake\/\">testing external APIs in Laravel with Http::fake<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq\">FAQ<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"faq-sdk\">Do I need an OpenAI PHP package for Laravel?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. A package saves some typing, but the API is plain JSON over HTTPS, and Laravel&#8217;s HTTP client handles it in a few lines. Going without one also means switching providers is mostly a config change, as long as the new one accepts the same request format.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"faq-queue-stream\">Should LLM calls be queued or streamed?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Queue them when nobody is watching the result arrive: summaries, classification, drafts for later review. Stream them when a person is waiting on the screen. Making a waiting user poll a queued job gives you the downsides of both.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"faq-timeout\">What timeout should I set?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Long enough for your slowest normal response and no longer. Start by measuring a few real calls for your prompt sizes, then set the HTTP timeout a bit above that and the job <code>$timeout<\/code> above the HTTP one, so the job can catch the error instead of being killed mid-request.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"faq-cost\">How do I keep LLM costs under control in Laravel?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Cap <code>max_tokens<\/code> per feature, throttle public endpoints, skip work that&#8217;s already been done, and record usage per feature so you can see where the money goes. Limiting how much text users can send in, like the <code>limit(500)<\/code> on the explain route, helps too.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"faq-key\">Where should the API key live?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In <code>.env<\/code> on the server, read through <code>config\/services.php<\/code>. Never in front-end code and never committed. The browser talks to your Laravel route, and only Laravel talks to the provider.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><em>I&#8217;m <a href=\"https:\/\/shaz3e.com\" target=\"_blank\" rel=\"noopener\">Shahrukh Akhtar (Shaz3e)<\/a>, CTO &amp; Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive &amp; Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on <a href=\"https:\/\/x.com\/shaz3e\" target=\"_blank\" rel=\"noopener\">X<\/a>, <a href=\"https:\/\/linkedin.com\/in\/shaz3e\" target=\"_blank\" rel=\"noopener\">LinkedIn<\/a>, <a href=\"https:\/\/peerlist.io\/shaz3e\" target=\"_blank\" rel=\"noopener\">Peerlist<\/a> and <a href=\"https:\/\/github.com\/Shaz3e\" target=\"_blank\" rel=\"noopener\">GitHub<\/a>.<\/em><\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>How to call OpenAI-style LLM APIs from Laravel 13 without an SDK: queued jobs with sensible retries, streamed answers over server-sent events, and a usage table that tracks tokens and cost per feature, all covered by Http::fake tests.<\/p>\n","protected":false},"author":2,"featured_media":318,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_kad_post_transparent":"","_kad_post_title":"","_kad_post_layout":"","_kad_post_sidebar_id":"","_kad_post_content_style":"","_kad_post_vertical_padding":"","_kad_post_feature":"","_kad_post_feature_position":"","_kad_post_header":false,"_kad_post_footer":false,"_kad_post_classname":"","_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_hide_featured_image":false,"_jetpack_featured_image_duplicate_dismissed":0,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[7],"tags":[104,28,117,25,53,105],"class_list":["post-317","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-laravel-php","tag-ai","tag-laravel","tag-openai","tag-php","tag-queues","tag-streaming"],"jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/phsTKQ-57","jetpack_featured_media_url":"https:\/\/i0.wp.com\/www.shaz3e.com\/blog\/wp-content\/uploads\/2026\/11\/laravel-llm-api-1200x630-1.jpg?fit=1200%2C630&ssl=1","_links":{"self":[{"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/posts\/317","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/comments?post=317"}],"version-history":[{"count":1,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/posts\/317\/revisions"}],"predecessor-version":[{"id":319,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/posts\/317\/revisions\/319"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/media\/318"}],"wp:attachment":[{"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/media?parent=317"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/categories?post=317"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/tags?post=317"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}