Laravel 12 - How To Integrate BotMan Chatbot

Touseef Afridi
12 Sep 25

Laravel 12 - How To Integrate BotMan Chatbot

In this tutorial, learn how to integrate BotMan Chatbot in Laravel 12 to create interactive chat solutions, automate conversations, and improve user engagement.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through integrating a BotMan chatbot into a Laravel project, step by step. It starts with setting up a fresh Laravel 12 project (or using an existing one), then moves on to installing the BotMan package along with the Web driver. Next, it explains how to configure caching for BotMan and set up the driver to handle web-based interactions. A route is then created to manage requests to the chatbot, and the view is updated with HTML to display the chat interface on your webpage. The guide also covers creating a controller to handle incoming messages, where the bot listens for a "hi" message and engages users by asking for their name and email. Finally, you’ll start the Laravel development server and test the chatbot in the browser, allowing users to interact by saying "hi" and providing their details.

Step # 1 : Set Up a New Laravel 12 Project.

We’ll begin by preparing a Laravel 12 application. If you don’t already have the Laravel installer available globally, install it with.
composer global require laravel/installer
This command gives you access to the laravel CLI tool, making it easier to spin up new projects. If it’s already installed, you can skip straight to creating a fresh project using the following command.
laravel new botman
During setup, you’ll be asked a few questions. Here’s what to choose.
  • For the starter kit, pick None.
  • When asked for testing, go with Pest.
  • Set the database option to MySQL.
  • Approve running migrations by typing yes.
  • Confirm installation and build by typing yes to run npm install + npm run build.

Once the process finishes, you’ll have a brand-new Laravel 12 project with Pest for testing, MySQL ready to go, and frontend assets compiled. At this point, your environment is fully set up and ready for development.

Step # 2 : Navigate to the Project.

Open your terminal (for example, Git Bash) and move into your Laravel project’s root directory.
cd c:xampp/htdocs/botman

Step # 3 : Install the Botman Package.

To add Botman to your Laravel project, run the following command.
composer require botman/botman
Running this will install the Botman package along with all its dependencies into your application. Once the process is complete, the package will be fully available for use, allowing you to start creating chatbots using Botman’s features. All necessary files and configuration settings will also be added to your vendor directory, so your project is ready for the next steps.

Step # 4 : Install the Botman Web Driver.

To enable web-based chat functionality, install the Botman Web driver by running.
composer require botman/driver-web
This command will add the Botman Web driver to your Laravel project, allowing your chatbot to interact with users directly on your website. Once the installation is complete, all required files and configuration settings for the Web driver will be added to your project, making it ready to start handling web-based chat interactions.

Step # 5 : Configure Cache for Botman.

Navigate to your Laravel project’s config directory and create a new folder named Botman. Inside this folder, create a file called config.php and add the following.
<?php
return [
    'conversation_cache_time' => 40,
    'user_cache_time' => 30,
];
?>
This setup defines the cache durations for Botman. The conversation_cache_time controls how long conversation data is stored, while user_cache_time specifies how long user information stays in the cache. Proper caching ensures smoother and faster chatbot interactions.

Step # 6 : Configure the Driver for Botman.

Next, configure Botman to use the Web driver. Inside the Botman folder that we created in Step 5, create a file named web.php and add.
<?php
return [
    'matchingData' => [
        'driver' => 'web',
    ],
];
?>
This configuration tells Botman to handle user interactions using the Web driver. The matchingData array specifies 'driver' => 'web', which is essential for enabling chat functionality directly on your website.

Step # 7 : Create a Route for Botman.

First, import the BotManController at the top of your routes file.
use App\Http\Controllers\BotManController;
Then, define a route that listens for both GET and POST requests at /botman and directs them to the handle method in BotManController.
Route::match(['get', 'post'], '/botman', 'App\Http\Controllers\BotManController@handle');
This route allows your application to manage chatbot interactions at the /botman URL. Both GET and POST requests will be handled, and the handle method in BotManController will process incoming messages and generate responses for the chatbot.

Step # 8 : Update the View.

To set up the Botman chatbot interface, replace the content of your welcome.blade.php file with the following.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 12 - Integrating BotMan Chatbot - Code Shotcut</title>
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
</head>
<body>
</body>
<!-- BotMan Widget CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/botman-web-widget@0/build/assets/css/chat.min.css">
<script>
    // BotMan Widget configuration
    var botmanWidget = {
        aboutText: 'Start the conversation with Hi', // Message shown in the widget header
        introMessage: "WELCOME TO CODE SHOTCUT" // Greeting message when chatbot loads
    };
</script>
<!-- BotMan Widget JS -->
<script src="https://cdn.jsdelivr.net/npm/botman-web-widget@0/build/js/widget.js"></script>
<script>
    // Auto-open chatbot panel after page load
    window.addEventListener("load", function () {
        setTimeout(function () {
            botmanChatWidget.open(); // Opens the chatbot automatically
        }, 1000); // Delay of 1 second before opening (optional)
    });
</script>
</html>
This code brings in all the required BotMan CSS and JavaScript to render the chatbot on your website. The introMessage serves as the greeting users see when the chatbot starts, and aboutText appears in the widget to encourage users to begin a conversation. With these settings, the chatbot panel will open automatically on page load, giving you a fully functional and nicely styled chatbot interface in your Laravel 12 application.

Step # 9 : Create the BotMan Controller.

Generate the BotManController by running the following command.
php artisan make:controller BotManController
Once the controller has been generated, open BotManController.php and replace its contents 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 incoming messages from the BotMan chatbot.
     */
    public function handle()
    {
        $botman = app('botman');
        // Listen for any incoming message
        $botman->hears('{message}', function($botman, $message) {
            // Convert message to lowercase for case-insensitive matching
            $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 prompt
            else {
                $botman->reply("Start a conversation by saying hi.");
            }
        });
        // Start listening for messages
        $botman->listen();
    }
    /**
     * Ask the user for their name when they say 'hi'.
     */
    public function askName($botman)
    {
        // Inline conversation to ask for name and email
        $botman->ask('Hello! What is your name?', function(Answer $answer, $conversation) {
            // Capture the user's name
            $name = $answer->getText();
            // Respond with a personalized greeting
            $this->say('Nice to meet you, ' . $name);
            // Continue the conversation by asking for email
            $conversation->ask('Can you advise about your email address?', function(Answer $answer, $conversation){
                $email = $answer->getText();
                $this->say('Email : ' . $email);
            });
        });
    }
}
The handle() method monitors all incoming messages from users. When someone types hi, it calls the askName() method, which begins a conversation by asking the user for their name. After receiving the name, the bot replies with a personalized greeting. The conversation then continues by requesting the user’s email address, and once provided, the bot displays it. For any other messages, the bot responds with a prompt to type hi to start the chat. This flow allows the bot to interact with users in a friendly and simple way, starting with a greeting and collecting basic personalized information.

Step # 10 : Test Your Chatbot

With everything in place, it’s time to test your BotMan chatbot. Start by running the Laravel development server.
php artisan serve
Once the server is up, open your browser and go to: 127.0.0.1:8000. When the page loads, you can start interacting with the chatbot. If a user types hi or Hi, the bot will respond by asking for their name and email, guiding them through the conversation flow.

For any other input, the chatbot will prompt the user to begin the chat by saying hi, ensuring that the interaction starts correctly. The interface will display all the responses and interactions as configured.

Conclusion

By following this guide, you have successfully integrated a BotMan chatbot into your Laravel application. Your chatbot can now interact with users by initiating conversations, asking for their name and email, and responding appropriately based on user input. The BotMan package along with the Web driver makes it straightforward to add chat functionality to your website. From here, you can enhance your chatbot by adding more conversational flows, connecting it with other services, or customizing its behavior to meet your specific needs.
For more information and advanced features, refer to the official BotMan documentation.

Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
1

0 Comments

To engage in commentary, kindly proceed by logging in or registering