Tech

How to Integrate Laravel and Bootstrap Real-Time Chatbot

Creating a real-time chatbot using Laravel and Bootstrap involves several steps. Here’s a high-level overview of the process:

  1. Set up Laravel project.
  2. Set up real-time functionality using Laravel Echo and Pusher.
  3. Create frontend with Bootstrap.
  4. Create necessary routes, controllers, and views.
  5. Integrate Pusher for real-time updates.

Here’s a step-by-step guide with code snippets:

Step 1: Set up the Laravel Project

First, create a new Laravel project:

composer create-project –prefer-dist laravel/laravel realtime-chatbot
cd realtime-chatbot

 

Step 2: Install Pusher and Laravel Echo

Install Pusher and Laravel Echo:

composer require pusher/pusher-php-server
npm install –save laravel-echo pusher-js

Step 3: Configure Pusher

Add your Pusher credentials to the .env file:

PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-app-key
PUSHER_APP_SECRET=your-pusher-app-secret
PUSHER_APP_CLUSTER=your-pusher-app-cluster

Update the config/broadcasting.php configuration file to use Pusher:

‘connections’ => [
‘pusher’ => [
‘driver’ => ‘pusher’,
‘key’ => env(‘PUSHER_APP_KEY’),
‘secret’ => env(‘PUSHER_APP_SECRET’),
‘app_id’ => env(‘PUSHER_APP_ID’),
‘options’ => [
‘cluster’ => env(‘PUSHER_APP_CLUSTER’),
‘useTLS’ => true,
],
],
// Other connections…
],

Step 4: Create Chat Components

Create the necessary database table for storing chat messages. Run the following artisan command to create a migration file:

php artisan make:migration create_messages_table

Update the migration file (database/migrations/xxxx_xx_xx_create_messages_table.php):

public function up()
{
Schema::create(‘messages’, function (Blueprint $table) {
$table->id();
$table->string(‘message’);
$table->timestamps();
});
}

Run the migration:

php artisan migrate

 

Create a model for the Message:

php artisan make:model Message

Step 5: Create Routes, Controllers, and Events

Define routes in routes/web.php:

use App\Http\Controllers\ChatController;

Route::get(‘/’, [ChatController::class, ‘index’]);
Route::post(‘/send-message’, [ChatController::class, ‘sendMessage’]);

 

Create the ChatController:

php artisan make:controller ChatController
Update ChatController.php:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Events\MessageSent;
use App\Models\Message;

class ChatController extends Controller
{
public function index()
{
$messages = Message::all();
return view(‘chat’, compact(‘messages’));
}

public function sendMessage(Request $request)
{
$message = Message::create([
‘message’ => $request->message
]);

event(new MessageSent($message));

return response()->json([‘status’ => ‘Message Sent!’]);
}
}

Create an event for broadcasting messages:

php artisan make:event MessageSent

Update MessageSent.php:

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
use App\Models\Message;

class MessageSent implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;

public $message;

public function __construct(Message $message)
{
$this->message = $message;
}

public function broadcastOn()
{
return new Channel(‘chat’);
}

public function broadcastAs()
{
return ‘message.sent’;
}
}

Step 6: Create the Frontend with Bootstrap

Create a Blade template for the chat UI (resources/views/chat.blade.php):

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Real-time Chatbot</title>
<link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css” rel=”stylesheet”>
<script src=”https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.5/dist/umd/popper.min.js”></script>
<script src=”https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js”></script>
<script src=”https://js.pusher.com/7.0/pusher.min.js”></script>
</head>
<body>
<div class=”container mt-5″>
<h2>Real-time Chatbot</h2>
<div id=”messages” class=”border p-3 mb-3″ style=”height: 300px; overflow-y: scroll;”>
@foreach($messages as $message)
<div>{{ $message->message }}</div>
@endforeach
</div>
<form id=”messageForm”>
<div class=”input-group mb-3″>
<input type=”text” class=”form-control” id=”message” placeholder=”Type your message”>
<button class=”btn btn-primary” type=”submit”>Send</button>
</div>
</form>
</div>

<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<script>
Pusher.logToConsole = true;

var pusher = new Pusher(‘{{ env(“PUSHER_APP_KEY”) }}’, {
cluster: ‘{{ env(“PUSHER_APP_CLUSTER”) }}’,
forceTLS: true
});

var channel = pusher.subscribe(‘chat’);
channel.bind(‘message.sent’, function(data) {
$(‘#messages’).append(‘<div>’ + data.message.message + ‘</div>’);
});

$(‘#messageForm’).submit(function(e) {
e.preventDefault();

var message = $(‘#message’).val();

$.post(‘/send-message’, {
_token: ‘{{ csrf_token() }}’,
message: message
}, function() {
$(‘#message’).val(”);
});
});
</script>
</body>
</html>

Step 7: Run the Application

Run the Laravel development server:

php artisan serve

Leave a Reply

Your email address will not be published. Required fields are marked *