cd /news/artificial-intelligence/adding-an-ai-chatbot-to-your-laravel… · home topics artificial-intelligence article
[ARTICLE · art-61651] src=dev.to ↗ pub= topic=artificial-intelligence verified=true sentiment=↑ positive

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

A Laravel developer demonstrates how to integrate an AI chatbot into a Laravel application using the OpenAI API and the openai-php/laravel package. The tutorial covers setting up the package, creating a ChatService to handle LLM logic, storing conversation history in the session, and implementing rate limiting. The approach avoids external microservices and relies solely on Laravel and an HTTP API.

read2 min views1 publishedJul 16, 2026

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 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

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

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:

// 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.
── more in #artificial-intelligence 4 stories · sorted by recency
── more on @openai 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
Live at https://your-agent.zahid.host
Get free account → Pricing
from €0/mo · no card required
LIVE [news/adding-an-ai-chatbot…] indexed:0 read:2min 2026-07-16 ·