{"id":22,"date":"2026-07-06T10:00:00","date_gmt":"2026-07-06T04:30:00","guid":{"rendered":"https:\/\/softcrony.com\/blog\/?p=22"},"modified":"2026-07-06T10:00:00","modified_gmt":"2026-07-06T04:30:00","slug":"chatgpt-api-laravel-integration-guide","status":"publish","type":"post","link":"https:\/\/softcrony.com\/blog\/chatgpt-api-laravel-integration-guide\/","title":{"rendered":"How to Use the ChatGPT API in a Laravel Application: A Practical Guide"},"content":{"rendered":"<p>AI isn&#8217;t coming to business software \u2014 it&#8217;s already here. And integrating it into your Laravel application is much simpler than most developers expect.<\/p>\n<p>This guide walks through a complete ChatGPT API integration in Laravel \u2014 from setup to real-world use cases you can deploy for clients today.<\/p>\n<h2>What We&#8217;re Building<\/h2>\n<p>By the end of this guide you&#8217;ll have a working Laravel service that:<\/p>\n<ul>\n<li>Connects to OpenAI&#8217;s ChatGPT API<\/li>\n<li>Sends prompts and receives responses<\/li>\n<li>Handles errors gracefully<\/li>\n<li>Can be extended for chat, content generation, or business automation<\/li>\n<\/ul>\n<h2>Prerequisites<\/h2>\n<ul>\n<li>Laravel 10 or 11 installed<\/li>\n<li>PHP 8.1+<\/li>\n<li>An OpenAI account with API access<\/li>\n<li>Basic familiarity with Laravel services and controllers<\/li>\n<\/ul>\n<h2>Step 1 \u2014 Get Your OpenAI API Key<\/h2>\n<p>Go to <a href=\"https:\/\/platform.openai.com\" target=\"_blank\" rel=\"noopener\">platform.openai.com<\/a>, sign in, and navigate to <strong>API Keys<\/strong>. Create a new secret key and copy it immediately \u2014 you won&#8217;t be able to see it again.<\/p>\n<p>Add it to your <code>.env<\/code> file:<\/p>\n<pre><code>OPENAI_API_KEY=sk-your-key-here\r\nOPENAI_MODEL=gpt-4o-mini<\/code><\/pre>\n<p>We use <code>gpt-4o-mini<\/code> as the default \u2014 it&#8217;s fast, affordable, and more than capable for most business use cases. Switch to <code>gpt-4o<\/code> for tasks requiring deeper reasoning.<\/p>\n<h2>Step 2 \u2014 Install the OpenAI PHP Client<\/h2>\n<p>The official OpenAI PHP package makes the API easy to work with:<\/p>\n<pre><code>composer require openai-php\/client<\/code><\/pre>\n<h2>Step 3 \u2014 Create a Laravel Service<\/h2>\n<p>Create a dedicated service class to keep your AI logic clean and reusable:<\/p>\n<pre><code>php artisan make:class Services\/OpenAIService<\/code><\/pre>\n<p>Open <code>app\/Services\/OpenAIService.php<\/code> and replace its contents with:<\/p>\n<pre><code>&lt;?php\r\n\r\nnamespace App\\Services;\r\n\r\nuse OpenAI;\r\nuse Exception;\r\nuse Illuminate\\Support\\Facades\\Log;\r\n\r\nclass OpenAIService\r\n{\r\n    protected $client;\r\n    protected string $model;\r\n\r\n    public function __construct()\r\n    {\r\n        $this-&gt;client = OpenAI::client(config('services.openai.key'));\r\n        $this-&gt;model = config('services.openai.model', 'gpt-4o-mini');\r\n    }\r\n\r\n    \/**\r\n     * Send a simple prompt and get a response.\r\n     *\/\r\n    public function ask(string $prompt, int $maxTokens = 500): string\r\n    {\r\n        try {\r\n            $response = $this-&gt;client-&gt;chat()-&gt;create([\r\n                'model'    =&gt; $this-&gt;model,\r\n                'messages' =&gt; [\r\n                    ['role' =&gt; 'user', 'content' =&gt; $prompt],\r\n                ],\r\n                'max_tokens'  =&gt; $maxTokens,\r\n                'temperature' =&gt; 0.7,\r\n            ]);\r\n\r\n            return $response-&gt;choices[0]-&gt;message-&gt;content ?? '';\r\n\r\n        } catch (Exception $e) {\r\n            Log::error('OpenAI API error: ' . $e-&gt;getMessage());\r\n            return 'Sorry, I could not process your request right now.';\r\n        }\r\n    }\r\n\r\n    \/**\r\n     * Chat with context \u2014 pass a full conversation history.\r\n     *\/\r\n    public function chat(array $messages, int $maxTokens = 1000): string\r\n    {\r\n        try {\r\n            $response = $this-&gt;client-&gt;chat()-&gt;create([\r\n                'model'       =&gt; $this-&gt;model,\r\n                'messages'    =&gt; $messages,\r\n                'max_tokens'  =&gt; $maxTokens,\r\n                'temperature' =&gt; 0.7,\r\n            ]);\r\n\r\n            return $response-&gt;choices[0]-&gt;message-&gt;content ?? '';\r\n\r\n        } catch (Exception $e) {\r\n            Log::error('OpenAI chat error: ' . $e-&gt;getMessage());\r\n            return 'Sorry, something went wrong.';\r\n        }\r\n    }\r\n}<\/code><\/pre>\n<h2>Step 4 \u2014 Register the API Key in Config<\/h2>\n<p>Add to <code>config\/services.php<\/code>:<\/p>\n<pre><code>'openai' =&gt; [\r\n    'key'   =&gt; env('OPENAI_API_KEY'),\r\n    'model' =&gt; env('OPENAI_MODEL', 'gpt-4o-mini'),\r\n],<\/code><\/pre>\n<h2>Step 5 \u2014 Create a Controller<\/h2>\n<pre><code>php artisan make:controller AIController<\/code><\/pre>\n<pre><code>&lt;?php\r\n\r\nnamespace App\\Http\\Controllers;\r\n\r\nuse App\\Services\\OpenAIService;\r\nuse Illuminate\\Http\\Request;\r\nuse Illuminate\\Http\\JsonResponse;\r\n\r\nclass AIController extends Controller\r\n{\r\n    public function __construct(\r\n        protected OpenAIService $ai\r\n    ) {}\r\n\r\n    \/**\r\n     * Simple single prompt endpoint.\r\n     *\/\r\n    public function ask(Request $request): JsonResponse\r\n    {\r\n        $request-&gt;validate([\r\n            'prompt' =&gt; 'required|string|max:2000',\r\n        ]);\r\n\r\n        $response = $this-&gt;ai-&gt;ask($request-&gt;input('prompt'));\r\n\r\n        return response()-&gt;json([\r\n            'success'  =&gt; true,\r\n            'response' =&gt; $response,\r\n        ]);\r\n    }\r\n\r\n    \/**\r\n     * Multi-turn chat endpoint.\r\n     *\/\r\n    public function chat(Request $request): JsonResponse\r\n    {\r\n        $request-&gt;validate([\r\n            'messages'           =&gt; 'required|array',\r\n            'messages.*.role'    =&gt; 'required|in:user,assistant,system',\r\n            'messages.*.content' =&gt; 'required|string',\r\n        ]);\r\n\r\n        $response = $this-&gt;ai-&gt;chat($request-&gt;input('messages'));\r\n\r\n        return response()-&gt;json([\r\n            'success'  =&gt; true,\r\n            'response' =&gt; $response,\r\n        ]);\r\n    }\r\n}<\/code><\/pre>\n<h2>Step 6 \u2014 Add Routes<\/h2>\n<p>In <code>routes\/api.php<\/code>:<\/p>\n<pre><code>use App\\Http\\Controllers\\AIController;\r\n\r\nRoute::post('\/ai\/ask', [AIController::class, 'ask']);\r\nRoute::post('\/ai\/chat', [AIController::class, 'chat']);<\/code><\/pre>\n<h2>Step 7 \u2014 Test It<\/h2>\n<p>Use a tool like Postman or Hoppscotch to test:<\/p>\n<pre><code>POST \/api\/ai\/ask\r\nContent-Type: application\/json\r\n\r\n{\r\n  \"prompt\": \"Explain what Laravel is in 2 sentences.\"\r\n}<\/code><\/pre>\n<p>Expected response:<\/p>\n<pre><code>{\r\n  \"success\": true,\r\n  \"response\": \"Laravel is a PHP web framework known for its elegant syntax and powerful features like Eloquent ORM, Blade templating, and built-in authentication. It follows the MVC pattern and is widely used for building everything from small APIs to large enterprise applications.\"\r\n}<\/code><\/pre>\n<h2>Real Business Use Cases<\/h2>\n<p>This foundation opens up dozens of practical applications for clients.<\/p>\n<p><strong>Automated customer support:<\/strong> Feed your product documentation to the system prompt and build a support chatbot that answers questions based on your actual content \u2014 no hallucination risk.<\/p>\n<p><strong>Invoice and document summarisation:<\/strong> Pass a long contract or invoice to the API and return a plain-English summary. Useful for legal, finance, and procurement teams.<\/p>\n<p><strong>Content generation pipelines:<\/strong> Automate first drafts of product descriptions, email campaigns, or blog outlines from structured data. A furniture retailer we work with generates product descriptions from SKU data \u2014 cutting content team workload by 60%.<\/p>\n<p><strong>Internal knowledge base:<\/strong> Connect the API to your company&#8217;s internal documentation and let staff ask questions in plain English instead of searching through folders.<\/p>\n<p><strong>Lead qualification:<\/strong> Analyse incoming enquiry forms and classify leads by industry, budget signals, and urgency \u2014 without a human reading every submission.<\/p>\n<h2>Cost Management Tips<\/h2>\n<p>OpenAI charges per token \u2014 roughly per word. Here&#8217;s how to keep costs predictable:<\/p>\n<ul>\n<li>Use <code>gpt-4o-mini<\/code> for high-volume, simple tasks \u2014 it costs a fraction of <code>gpt-4o<\/code><\/li>\n<li>Always set <code>max_tokens<\/code> \u2014 without a limit, a single request can run very long<\/li>\n<li>Cache responses for identical prompts using Laravel&#8217;s cache layer<\/li>\n<li>Log token usage per request so you can track costs per feature<\/li>\n<\/ul>\n<pre><code>\/\/ Example: cache repeated prompts for 1 hour\r\n$cacheKey = 'ai_response_' . md5($prompt);\r\n\r\n$response = cache()-&gt;remember($cacheKey, 3600, function () use ($prompt) {\r\n    return $this-&gt;ai-&gt;ask($prompt);\r\n});<\/code><\/pre>\n<h2>A Note on Data Privacy<\/h2>\n<p>Before sending any client or user data to the OpenAI API, check your privacy policy and terms of service. OpenAI does not use API inputs for training by default, but your clients may have specific data residency requirements \u2014 especially in regulated industries like healthcare or finance.<\/p>\n<p>For sensitive use cases, consider running an open-source model locally using tools like Ollama \u2014 we can cover that in a future post.<\/p>\n<h2>What&#8217;s Next<\/h2>\n<p>This integration is the foundation. From here you can add streaming responses for real-time chat UI, function calling for structured outputs, and RAG (Retrieval Augmented Generation) to ground responses in your own data.<\/p>\n<p>If you want to integrate AI into your existing Laravel application or build a custom AI-powered tool for your business, <a href=\"https:\/\/softcrony.com\/contact\/\">our team is happy to help<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>AI isn&#8217;t coming to business software \u2014 it&#8217;s already here. And integrating it into your Laravel application is much simpler than most developers expect. This guide walks through a complete ChatGPT API integration in Laravel \u2014 from setup to real-world use cases you can deploy for clients today. What We&#8217;re Building By the end of [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":23,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[27,31,28,19,29,30,18],"class_list":["post-22","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ai-automation","tag-ai","tag-ai-automation","tag-chatgpt","tag-laravel","tag-openai","tag-php","tag-web-development"],"_links":{"self":[{"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/posts\/22","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/comments?post=22"}],"version-history":[{"count":3,"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/posts\/22\/revisions"}],"predecessor-version":[{"id":26,"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/posts\/22\/revisions\/26"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/media\/23"}],"wp:attachment":[{"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/media?parent=22"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/categories?post=22"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/softcrony.com\/blog\/wp-json\/wp\/v2\/tags?post=22"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}