Welcome to the next step in our journey of building a chatbot service with Laravel. In the previous lesson, we explored the ChatService
class, which acts as a bridge between managing chat data and generating AI responses. Now, we will focus on the ChatController
, a crucial component that manages chat sessions and handles messages by interacting with both the model and service layers. The controller is responsible for orchestrating the flow of data between the user interface and the backend services, ensuring that user interactions are processed efficiently and effectively.
The ChatController
class is the heart of our controller layer. It is responsible for managing chat sessions and processing user messages. Let's begin by examining the structure of the ChatController
class.
php1<?php 2 3namespace App\Http\Controllers; 4 5use Illuminate\Http\Request; 6use Illuminate\Support\Facades\Session; 7use App\Services\ChatService; 8use Illuminate\Support\Str; 9 10class ChatController extends Controller 11{ 12 protected $chatService; 13 14 public function __construct(ChatService $chatService) 15 { 16 $this->chatService = $chatService; 17 } 18}
In this snippet, we:
- Use Laravel's
Session
facade for session management. - Use
Str
for generating unique identifiers. - Import the
ChatService
class for managing chat data and processing messages. - Initialize the
ChatController
with an instance ofChatService
.
Before creating a chat, we need to ensure that a user session exists. The ensureUserSession
method checks if a user ID is present in the session. If not, it generates a new user ID.
php1public function ensureUserSession() 2{ 3 if (!Session::has('user_id')) { 4 Session::put('user_id', (string) Str::uuid()); 5 } 6 return Session::get('user_id'); 7}
This method ensures that a user session is available by checking the session for a user_id
. If it doesn't exist, a new user ID is generated and stored in the session.
One of the primary responsibilities of the ChatController
is to create new chat sessions. The createChat
method simulates a chat creation request.
php1public function createChat(Request $request) 2{ 3 $userId = Session::get('user_id'); 4 if (!$userId) { 5 return response()->json(['error' => 'Session expired'], 401); 6 } 7 8 $chatId = $this->chatService->createChat($userId); 9 return response()->json([ 10 'chat_id' => $chatId, 11 'message' => 'Chat created successfully' 12 ]); 13}
In this method, we:
-
Retrieve the
user_id
: We first check the session for auser_id
. -
Handle Session Expiry: If the session has expired (i.e., no
user_id
is found), we return an error response:response()->json(['error' => 'Session expired'], 401)
. This approach ensures that the client can handle the error gracefully, providing a better user experience. -
Create a Chat Session: If the session is valid, we call the
createChat
method of theChatService
with the user ID to create a new chat session. We then return a response containing a unique chat ID and a success message.
The sendMessage
method is responsible for processing user messages and returning the AI's response or an error message.
php1public function sendMessage(Request $request, $chatId) 2{ 3 $userId = Session::get('user_id'); 4 if (!$userId) { 5 return response()->json(['error' => 'Session expired'], 401); 6 } 7 8 $userMessage = $request->input('message'); 9 if (!$chatId || !$userMessage) { 10 return response()->json(['error' => 'Missing chat_id or message'], 400); 11 } 12 13 try { 14 $aiResponse = $this->chatService->processMessage($userId, $chatId, $userMessage); 15 return response()->json(['message' => $aiResponse]); 16 } catch (\Exception $e) { 17 return response()->json(['error' => $e->getMessage()], 500); 18 } 19}
In this method, we first check if the user session is valid. We then ensure that both chat_id
and user_message
are provided. If any are missing, an error is returned. The method attempts to process the message using the processMessage
method of the ChatService
. If successful, the AI's response is returned. If an exception occurs, an appropriate error message is returned.
To see the ChatController
in action, let's integrate it into the main application. This example demonstrates how to create a chat session and handle a user message, showcasing the controller's functionality.
php1// In routes/web.php 2 3use App\Http\Controllers\ChatController; 4 5Route::get('/ensure-session', [ChatController::class, 'ensureUserSession']); 6Route::post('/create-chat', [ChatController::class, 'createChat']); 7Route::post('/send-message/{chatId}', [ChatController::class, 'sendMessage']);
In this example, we define routes for ensuring a user session, creating a chat session, and sending a message. These routes map to the corresponding methods in the ChatController
, allowing us to handle requests and demonstrate the controller's functionality.
In this lesson, we explored the ChatController
class and its role in managing chat sessions and handling user messages. We learned how to implement the controller, create chat sessions, and process messages using the ChatService
. The controller is a vital component of our chatbot application, ensuring that user interactions are managed efficiently and effectively.
As you move on to the practice exercises, take the opportunity to experiment with the ChatController
's functionality. This hands-on practice will reinforce the concepts covered in this lesson and prepare you for the next steps in our course. Keep up the great work, and I look forward to seeing your progress!