HomePortfolioNewsGalleryContact
LaravelChatbotOpenAI

Building a Chatbot in Laravel from Scratch

By Aditya Nursyahbani5 min read48
Share:
Building a Chatbot in Laravel from Scratch

Chatbots are no longer limited to large tech companies. Today, businesses of all sizes use chatbot systems to automate customer support, improve response times, handle repetitive tasks, and create better user experiences across websites and applications. From simple FAQ assistants to AI-powered conversational platforms, chatbots have become an important part of modern web development.

Laravel is one of the best frameworks for building chatbot applications because it provides a clean architecture, powerful routing, database abstraction, queue support, and seamless API integration. Whether you want to build a simple rule-based chatbot or integrate advanced AI services like OpenAI, Laravel offers a flexible foundation that can scale with your application needs.

In this tutorial, you will learn how to build a chatbot in Laravel from scratch using database storage, API endpoints, conversation management, and optional AI integration. We will create a simple but scalable chatbot system step by step, starting from database design all the way to building a frontend chat interface.

By the end of this guide, you will understand how to:

  • Create chatbot APIs in Laravel
  • Store conversations and messages in a database
  • Build rule-based chatbot responses
  • Integrate AI-powered replies using external APIs
  • Create a simple frontend chat interface
  • Structure a scalable chatbot application architecture

This tutorial is beginner-friendly but also includes practical patterns that can be used in real-world Laravel applications.


Why Laravel?

  • Clean MVC architecture
  • Powerful routing system
  • Easy API development
  • Strong ecosystem for scaling applications

Step 1: Create Laravel Project

bash
composer create-project laravel/laravel laravel-chatbot cd laravel-chatbot php artisan migrate

Step 2: Database Structure

We need two tables to store conversations and messages.

Conversations Table

php
<?php Schema::create('conversations', function (Blueprint $table) { $table->id(); $table->string('user_id')->nullable(); $table->timestamps(); });

Messages Table

php
<?php Schema::create('messages', function (Blueprint $table) { $table->id(); $table->foreignId('conversation_id')->constrained()->onDelete('cascade'); $table->enum('sender', ['user', 'bot']); $table->text('message'); $table->timestamps(); });

Step 3: Chatbot Controller

php
<?php public function sendMessage(Request $request) { $conversation = Conversation::firstOrCreate([ 'user_id' => $request->user_id ?? 'guest' ]); Message::create([ 'conversation_id' => $conversation->id, 'sender' => 'user', 'message' => $request->message ]); $response = $this->generateResponse($request->message); Message::create([ 'conversation_id' => $conversation->id, 'sender' => 'bot', 'message' => $response ]); return response()->json([ 'reply' => $response ]); }

Step 4: Rule-Based Logic

php
<?php private function generateResponse($message) { $message = strtolower($message); if (str_contains($message, 'hello')) { return "Hi! How can I help you today?"; } if (str_contains($message, 'price')) { return "Our pricing starts from $10/month."; } if (str_contains($message, 'support')) { return "You can contact support@example.com"; } return "Sorry, I didn't understand that. Can you rephrase?"; }

Step 5: API Route

php
<?php Route::post('/chat/send', [ChatbotController::class, 'sendMessage']);

Step 6: Optional AI Integration

php
<?php use Illuminate\Support\Facades\Http; private function aiResponse($message) { $response = Http::withHeaders([ 'Authorization' => 'Bearer YOUR_API_KEY' ])->post('https://api.openai.com/v1/chat/completions', [ 'model' => 'gpt-4o-mini', 'messages' => [ ['role' => 'user', 'content' => $message] ] ]); return $response['choices'][0]['message']['content'] ?? 'No response'; }

Step 7: Frontend Chat UI

javascript
document.getElementById('chatForm').addEventListener('submit', async (e) => { e.preventDefault(); let message = document.getElementById('message').value; let res = await fetch('/api/chat/send', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({message}) }); let data = await res.json(); console.log(data.reply); });

Conclusion

Laravel makes it easy to build scalable chatbot systems. You can start with simple rule-based logic and evolve into an AI-powered assistant for production use.