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"
Step 2: .env
OPENAI_API_KEY=sk-proj-...
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;
}
}
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]]]);
}
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']);
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);
}
Testing
OpenAI::fake([CreateResponse::fake(['choices' => [['message' => ['content' => 'Hi!']]]])]);
$reply = app(OpenAIService::class)->chat([['role' => 'user', 'content' => 'Hello']]);
$this->assertEquals('Hi!', $reply);
Summary
-
composer require openai-php/laravel+OPENAI_API_KEYin.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)