DEV Community

Cover image for How to Integrate OpenAI API with Laravel (Complete Guide 2026)
Serhii Kalyna
Serhii Kalyna

Posted on • Originally published at kalyna.pro

How to Integrate OpenAI API with Laravel (Complete Guide 2026)

How to Integrate OpenAI API with Laravel (Complete Guide 2026)

Laravel is the most popular PHP framework, and adding OpenAI to it is straightforward with the official openai-php/client library. This guide covers installation, a service class, a chat controller, streaming, error handling, and testing.

Requirements

  • Laravel 10 or 11, PHP 8.1+, Composer, OpenAI API key

Step 1: Install

composer require openai-php/laravel
php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"
Enter fullscreen mode Exit fullscreen mode

Step 2: .env

OPENAI_API_KEY=sk-proj-...
Enter fullscreen mode Exit fullscreen mode

Step 3: OpenAIService

namespace App\Services;
use OpenAI\Laravel\Facades\OpenAI;

class OpenAIService
{
    public function chat(array $messages, string $model = 'gpt-4o-mini'): string
    {
        $response = OpenAI::chat()->create(['model' => $model, 'messages' => $messages]);
        return $response->choices[0]->message->content;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: ChatController

public function send(Request $request): JsonResponse
{
    $messages = $request->input('history', []);
    $messages[] = ['role' => 'user', 'content' => $request->input('message')];
    $reply = $this->openAI->chat($messages);
    return response()->json(['reply' => $reply, 'messages' => [...$messages,
        ['role' => 'assistant', 'content' => $reply]]]);
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Streaming SSE

return response()->stream(function () use ($messages) {
    foreach ($this->openAI->stream($messages) as $chunk) {
        echo "data: " . json_encode(['chunk' => $chunk]) . "\n\n";
        ob_flush(); flush();
    }
    echo "data: [DONE]\n\n";
}, 200, ['Content-Type' => 'text/event-stream', 'Cache-Control' => 'no-cache']);
Enter fullscreen mode Exit fullscreen mode

Error Handling

use OpenAI\Exceptions\ErrorException;
use OpenAI\Exceptions\TransporterException;

try {
    $reply = $this->openAI->chat($messages);
} catch (ErrorException $e) {
    return response()->json(['error' => 'AI service error.'], 503);
} catch (TransporterException $e) {
    return response()->json(['error' => 'Connection failed.'], 503);
}
Enter fullscreen mode Exit fullscreen mode

Testing

OpenAI::fake([CreateResponse::fake(['choices' => [['message' => ['content' => 'Hi!']]]])]);
$reply = app(OpenAIService::class)->chat([['role' => 'user', 'content' => 'Hello']]);
$this->assertEquals('Hi!', $reply);
Enter fullscreen mode Exit fullscreen mode

Summary

  • composer require openai-php/laravel + OPENAI_API_KEY in .env
  • Service class keeps controllers clean; stream with response()->stream() + SSE
  • OpenAI::fake() for unit tests without hitting the real API

Originally published at kalyna.pro

Top comments (0)