How to Use the ChatGPT API in a Laravel Application: A Practical Guide

calendar_today July 6, 2026
person info@softcrony.com

AI isn’t coming to business software — it’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 — from setup to real-world use cases you can deploy for clients today.

What We’re Building

By the end of this guide you’ll have a working Laravel service that:

  • Connects to OpenAI’s ChatGPT API
  • Sends prompts and receives responses
  • Handles errors gracefully
  • Can be extended for chat, content generation, or business automation

Prerequisites

  • Laravel 10 or 11 installed
  • PHP 8.1+
  • An OpenAI account with API access
  • Basic familiarity with Laravel services and controllers

Step 1 — Get Your OpenAI API Key

Go to platform.openai.com, sign in, and navigate to API Keys. Create a new secret key and copy it immediately — you won’t be able to see it again.

Add it to your .env file:

OPENAI_API_KEY=sk-your-key-here
OPENAI_MODEL=gpt-4o-mini

We use gpt-4o-mini as the default — it’s fast, affordable, and more than capable for most business use cases. Switch to gpt-4o for tasks requiring deeper reasoning.

Step 2 — Install the OpenAI PHP Client

The official OpenAI PHP package makes the API easy to work with:

composer require openai-php/client

Step 3 — Create a Laravel Service

Create a dedicated service class to keep your AI logic clean and reusable:

php artisan make:class Services/OpenAIService

Open app/Services/OpenAIService.php and replace its contents with:

<?php

namespace App\Services;

use OpenAI;
use Exception;
use Illuminate\Support\Facades\Log;

class OpenAIService
{
    protected $client;
    protected string $model;

    public function __construct()
    {
        $this->client = OpenAI::client(config('services.openai.key'));
        $this->model = config('services.openai.model', 'gpt-4o-mini');
    }

    /**
     * Send a simple prompt and get a response.
     */
    public function ask(string $prompt, int $maxTokens = 500): string
    {
        try {
            $response = $this->client->chat()->create([
                'model'    => $this->model,
                'messages' => [
                    ['role' => 'user', 'content' => $prompt],
                ],
                'max_tokens'  => $maxTokens,
                'temperature' => 0.7,
            ]);

            return $response->choices[0]->message->content ?? '';

        } catch (Exception $e) {
            Log::error('OpenAI API error: ' . $e->getMessage());
            return 'Sorry, I could not process your request right now.';
        }
    }

    /**
     * Chat with context — pass a full conversation history.
     */
    public function chat(array $messages, int $maxTokens = 1000): string
    {
        try {
            $response = $this->client->chat()->create([
                'model'       => $this->model,
                'messages'    => $messages,
                'max_tokens'  => $maxTokens,
                'temperature' => 0.7,
            ]);

            return $response->choices[0]->message->content ?? '';

        } catch (Exception $e) {
            Log::error('OpenAI chat error: ' . $e->getMessage());
            return 'Sorry, something went wrong.';
        }
    }
}

Step 4 — Register the API Key in Config

Add to config/services.php:

'openai' => [
    'key'   => env('OPENAI_API_KEY'),
    'model' => env('OPENAI_MODEL', 'gpt-4o-mini'),
],

Step 5 — Create a Controller

php artisan make:controller AIController
<?php

namespace App\Http\Controllers;

use App\Services\OpenAIService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class AIController extends Controller
{
    public function __construct(
        protected OpenAIService $ai
    ) {}

    /**
     * Simple single prompt endpoint.
     */
    public function ask(Request $request): JsonResponse
    {
        $request->validate([
            'prompt' => 'required|string|max:2000',
        ]);

        $response = $this->ai->ask($request->input('prompt'));

        return response()->json([
            'success'  => true,
            'response' => $response,
        ]);
    }

    /**
     * Multi-turn chat endpoint.
     */
    public function chat(Request $request): JsonResponse
    {
        $request->validate([
            'messages'           => 'required|array',
            'messages.*.role'    => 'required|in:user,assistant,system',
            'messages.*.content' => 'required|string',
        ]);

        $response = $this->ai->chat($request->input('messages'));

        return response()->json([
            'success'  => true,
            'response' => $response,
        ]);
    }
}

Step 6 — Add Routes

In routes/api.php:

use App\Http\Controllers\AIController;

Route::post('/ai/ask', [AIController::class, 'ask']);
Route::post('/ai/chat', [AIController::class, 'chat']);

Step 7 — Test It

Use a tool like Postman or Hoppscotch to test:

POST /api/ai/ask
Content-Type: application/json

{
  "prompt": "Explain what Laravel is in 2 sentences."
}

Expected response:

{
  "success": true,
  "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."
}

Real Business Use Cases

This foundation opens up dozens of practical applications for clients.

Automated customer support: Feed your product documentation to the system prompt and build a support chatbot that answers questions based on your actual content — no hallucination risk.

Invoice and document summarisation: Pass a long contract or invoice to the API and return a plain-English summary. Useful for legal, finance, and procurement teams.

Content generation pipelines: 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 — cutting content team workload by 60%.

Internal knowledge base: Connect the API to your company’s internal documentation and let staff ask questions in plain English instead of searching through folders.

Lead qualification: Analyse incoming enquiry forms and classify leads by industry, budget signals, and urgency — without a human reading every submission.

Cost Management Tips

OpenAI charges per token — roughly per word. Here’s how to keep costs predictable:

  • Use gpt-4o-mini for high-volume, simple tasks — it costs a fraction of gpt-4o
  • Always set max_tokens — without a limit, a single request can run very long
  • Cache responses for identical prompts using Laravel’s cache layer
  • Log token usage per request so you can track costs per feature
// Example: cache repeated prompts for 1 hour
$cacheKey = 'ai_response_' . md5($prompt);

$response = cache()->remember($cacheKey, 3600, function () use ($prompt) {
    return $this->ai->ask($prompt);
});

A Note on Data Privacy

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 — especially in regulated industries like healthcare or finance.

For sensitive use cases, consider running an open-source model locally using tools like Ollama — we can cover that in a future post.

What’s Next

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.

If you want to integrate AI into your existing Laravel application or build a custom AI-powered tool for your business, our team is happy to help.

Leave a comment