# Adding an AI Chatbot to Your Laravel App with the OpenAI API

> Source: <https://dev.to/adityakdevin/adding-an-ai-chatbot-to-your-laravel-app-with-the-openai-api-h0f>
> Published: 2026-07-16 07:32:50+00:00

Every product I've worked on in the last two years has eventually gotten the same request: *"Can we add an AI assistant to this?"* As a Laravel developer, the good news is that shipping a production-ready chatbot takes an afternoon — no Python microservice, no LangChain, just Laravel and an HTTP API.

In this tutorial we'll build a chatbot that:

The community-maintained [ openai-php/laravel](https://github.com/openai-php/laravel) package is the de-facto standard:

```
composer require openai-php/laravel
php artisan openai:install
```

Add your key to `.env`

:

```
OPENAI_API_KEY=sk-your-key-here
```

💡 Never commit the key. Use your host's secret manager in production.

Keep the LLM logic out of your controller. Create `app/Services/ChatService.php`

:

``` php
<?php

namespace App\Services;

use OpenAI\Laravel\Facades\OpenAI;

class ChatService
{
    private const SYSTEM_PROMPT = <<<'PROMPT'
        You are the helpful assistant for Acme Inc's customer portal.
        Answer only questions about the product. Be concise.
        If you don't know the answer, say so and suggest contacting support.
        PROMPT;

    /**
     * @param array<int, array{role: string, content: string}> $history
     */
    public function reply(array $history, string $userMessage): string
    {
        $messages = [
            ['role' => 'system', 'content' => self::SYSTEM_PROMPT],
            ...$history,
            ['role' => 'user', 'content' => $userMessage],
        ];

        $response = OpenAI::chat()->create([
            'model' => 'gpt-4o-mini',
            'messages' => $messages,
            'max_tokens' => 500,
        ]);

        return $response->choices[0]->message->content;
    }
}
```

Session-based history keeps things simple — no migrations needed for v1:

``` php
<?php

namespace App\Http\Controllers;

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

class ChatController extends Controller
{
    public function __invoke(Request $request, ChatService $chat): JsonResponse
    {
        $validated = $request->validate([
            'message' => ['required', 'string', 'max:2000'],
        ]);

        $history = $request->session()->get('chat_history', []);

        $answer = $chat->reply($history, $validated['message']);

        // keep the last 10 exchanges to control token costs
        $history[] = ['role' => 'user', 'content' => $validated['message']];
        $history[] = ['role' => 'assistant', 'content' => $answer];
        $request->session()->put('chat_history', array_slice($history, -20));

        return response()->json(['answer' => $answer]);
    }
}
```

Route it — **with rate limiting**, because every request costs you money:

``` php
// routes/web.php
use App\Http\Controllers\ChatController;

Route::post('/chat', ChatController::class)
    ->middleware(['auth', 'throttle:20,1']); // 20 req/min per user
```

Drop this into any Blade view — no framework required:

```
<div id="chat">
    <div id="messages"></div>
    <form id="chat-form">
        <input id="chat-input" type="text" placeholder="Ask me anything…" required />
        <button type="submit">Send</button>
    </form>
</div>

<script>
document.getElementById('chat-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const input = document.getElementById('chat-input');
    const messages = document.getElementById('messages');

    messages.insertAdjacentHTML('beforeend', `<p><b>You:</b> ${input.value}</p>`);

    const res = await fetch('/chat', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
        },
        body: JSON.stringify({ message: input.value }),
    });

    const { answer } = await res.json();
    messages.insertAdjacentHTML('beforeend', `<p><b>Bot:</b> ${answer}</p>`);
    input.value = '';
});
</script>
```

Before you ship this to real users:

`chat_logs`

table pays for itself the first time you debug a weird answer.`max_tokens`

`OpenAI::chat()->createStreamed()`

+ Server-Sent Events makes the bot feel 10x faster.*I'm Aditya Kumar ( adityakdevin) — Tech Lead & full-stack developer building AI-powered web products with Laravel, Vue, and LLM APIs. Find me at adityadev.in.*
