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

Published: (June 11, 2026 at 04:35 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to

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

              [![Serhii Kalyna](https://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3919650%2F44c55224-1c4c-4ef8-9544-d23b5d5d18f2.png)](https://dev.to/kalyna_pro)
              
              
            
      

      
            

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

0 views
Back to Blog

Related posts

Read more »

The spec is in the wrong place

My day job is at a large tech company. Hundreds of engineering teams, and every one of them is somewhere different on AI adoption. Some are still treating codin...

The Heuristics Say Don't

A culture that only records its disasters ends up with a biased archive. Wars documented, plagues chronicled, collapses catalogued. The quiet decades go unwritt...