Laravel 11 - BotMan Chatbot Integration
Laravel 11 - BotMan Chatbot Integration
In this tutorial, we’ll explore integrating BotMan Chatbot into Laravel 11, enhancing user engagement through automated conversations and providing seamless customer interactions.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
This guide provides a step-by-step process for integrating a BotMan chatbot into a Laravel project. It begins with setting up a fresh Laravel project or using an existing one, followed by installing the BotMan package and the BotMan Web driver. The guide then covers configuring the cache for BotMan and setting up the BotMan driver for web interactions. After that, a route is created to handle requests to the chatbot. The view is updated with HTML to display the chatbot interface on the webpage, and a controller is created to handle incoming messages and initiate conversations. The controller listens for a "hi" message and asks the user for their name and email. Finally, the Laravel development server is started, and the chatbot is tested by interacting with it through the browser, where users can start conversations by saying "hi" and providing their details.
Step # 1 : Create fresh Laravel project or use existing project.
If Laravel is installed globally, create a new project by running.
laravel new botman
Or
Alternatively, use Composer to create the project
composer create-project laravel/laravel --prefer-dist botman
During the setup process, make the following selections when prompted.
- Would you like to install the starter kit? — Select None
- Testing framework — Select Pest
- Database for your application — Select MySQL
- Run the default database migration — Type yes
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
cd c:xampp/htdocs/botman
Step # 3 : Install Botman package.
To install the Botman package, run the following command.
composer require botman/botman
Executing this command will install the Botman package and its dependencies into your Laravel project. Once the installation is complete, the package will be available for use in your application, and you'll be able to start building chatbots using Botman’s features. The required files and configuration settings will also be added to your vendor directory.
Step # 4 : Install Botman driver.
To install the Botman Web driver, run the following command.
composer require botman/driver-web
Running this command will install the Botman Web driver, allowing you to add web-based chat capabilities to your Laravel project. With this driver, your chatbot can interact with users directly on your website. After installation, the necessary files and configurations for the Web driver will be set up in your project.
Step # 5 : Configure Cache for Botman.
First, navigate to your Laravel project's config directory and create a new folder named Botman. Inside this folder, create a new file called config.php. In the config.php file, paste the following code.
<?php
return [
'conversation_cache_time' => 40,
'user_cache_time' => 30,
];
?>
This configuration will set the cache duration for both conversations and users. The conversation_cache_time option defines how long the conversation data will be cached, while the user_cache_time determines how long user data is stored in the cache.
Step # 6 : Configure driver for Botman.
In this step, you'll configure the Botman driver to use the web driver. To do this, create a new file inside the Botman directory, named web.php. Once the file is created, paste the following code.
<?php
return [
'matchingData' => [
'driver' => 'web',
],
];
This configuration ensures that Botman uses the web driver for handling interactions with users through web-based chat interfaces. The matchingData array specifies the driver type as web, which is necessary for web-based chatbot functionality.
Step # 7 : Create a Route.
To set up the route for handling Botman requests, first import the BotManController class at the top of your routes file.
use App\Http\Controllers\BotManController;
Next, define a route that listens for both GET and POST requests at the /botman URL and passes the requests to the handle method in the BotManController. Use the following code.
Route::match(['get', 'post'], '/botman', 'App\Http\Controllers\BotManController@handle');
This route will allow your application to handle chatbot interactions at the /botman URL, enabling it to respond to both GET and POST requests. The handle method in BotManController will process these requests and manage the chatbot’s response.
Step # 8 : Update View.
To set up the Botman chatbot interface, replace the content of the welcome.blade.php file with the following HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel 11 - BotMan Chatbot - Code Shotcut</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
</head>
<body>
</body>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/botman-web-widget@0/build/assets/css/chat.min.css">
<script>
var botmanWidget = {
aboutText: 'Start the conversation with Hi',
introMessage: "WELCOME TO CODE SHOTCUT"
};
</script>
<script src="https://cdn.jsdelivr.net/npm/botman-web-widget@0/build/js/widget.js"></script>
</html>
This code includes the necessary BotMan CSS and JavaScript to display the chatbot on your website. The introMessage is the greeting message shown when the chatbot is loaded, and aboutText is the message that prompts users to start the conversation. The widget will be styled and functional with these configurations.
Step # 9 : Create a controller.
Run the following command to generate the BotManController.
php artisan make:controller BotManController
Once the controller is created, replace the content of BotManController.php with the following code.
<?php
namespace App\Http\Controllers;
use BotMan\BotMan\BotMan;
use Illuminate\Http\Request;
use BotMan\BotMan\Messages\Incoming\Answer;
class BotManController extends Controller
{
/**
* Handle the incoming messages from the Botman chatbot.
*/
public function handle()
{
$botman = app('botman');
// Listen for any message
$botman->hears('{message}', function($botman, $message) {
// Convert the message to lowercase to handle case insensitivity
$message = strtolower($message);
// If the user says 'hi', start a conversation to ask for their name
if ($message == 'hi') {
$this->askName($botman);
}
// For any other input, send a default message
else {
$botman->reply("Start a conversation by saying hi.");
}
});
$botman->listen();
}
/**
* Ask the user for their name when they say 'hi'.
*/
public function askName($botman)
{
// For fewer questions, you can use the inline conversation approach as shown below. Alternatively, use a dedicated conversation class for multi-step conversations
$botman->ask('Hello! What is your name?', function(Answer $answer, $conversation) {
// Capture the user's answer
$name = $answer->getText();
// Respond with a personalized message
$this->say('Nice to meet you, ' . $name);
//Continue inline conversation.
$conversation->ask('Can you advise about your email address.', function(Answer $answer, $conversation){
$email = $answer->getText();
$this->say('Email : '.$email);
});
});
}
}
The handle() method listens for incoming messages from the user. When the user types hi, it triggers the askName() method, which starts a conversation asking the user for their name. After the user provides their name, the bot responds with a personalized greeting. Then, the askName() method continues by asking the user for their email address, and once the user responds, it displays the email. If the user sends any other message, the handle() method replies with a prompt to say hi to start the conversation. This setup allows the bot to engage users in a simple, interactive flow, starting with a hi and leading to personalized information like the user's name and email.
Step # 10 : It's time to test.
Now that everything is set up, it's time to test your chatbot. First, start the Laravel development server by running the following command.
php artisan serve
After the server starts, open your browser and navigate to the following URL.
127.0.0.1:8000
Once the page loads, you can interact with the chatbot. If a user says hi or Hi, the chatbot will respond by asking for their name and email.
If the user says anything else, the chatbot will prompt them to start the conversation by saying hi.
Conclusion
By following this guide, you've successfully integrated a BotMan chatbot into your Laravel application. Your chatbot is now capable of interacting with users by initiating a conversation, asking for their name and email, and responding appropriately based on user input. The BotMan package and Web driver simplify the process of adding chat functionality to your website, and with a few modifications, you can expand the chatbot's capabilities to handle more complex interactions. You can further enhance the chatbot by adding additional conversational flows, integrating with other services, and customizing its behavior to suit your needs.
For more details, refer to the BotMan documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
2 Comments
Great tutorial, thank you. I followed your instructions, I am getting error 404 page not found. Any advice?.
Hi Mohammed,
The 404 error indicates that Laravel is unable to locate the route you set up or that there might be a misconfiguration. I recommend reviewing each step again, and please let me know if anything is unclear. If you’re still unable to resolve the issue, feel free to email me at codeshotcut@gmail.com, and I’ll be happy to assist you further.