Integrating Laravel WebSocket with a database is a crucial part of building real-time applications like Chat, instant notifications, and event tracking. By combining WebSocket with a database, we can effectively store and manage real-time data. Here's how to integrate Laravel WebSocket with a database.
Step 1: Install Laravel WebSocket Package
Firstly, install and configure the laravel-websockets
package. Use Composer to install the package:
composer require beyondcode/laravel-websockets
Once installed, you need to publish the configuration files and perform necessary tasks:
php artisan vendor:publish --tag=websockets-config
php artisan migrate
Step 2: Create Database Table for Messages
We'll create a table in the database to store messages. Use the following command to create the messages
table:
php artisan make:model Message -m
After running the command, you'll see a migration file created in the database/migrations
directory. Open the migration file and define the structure of the messages
table:
// database/migrations/xxxx_xx_xx_create_messages_table.php
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->text('content');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
Run the migration command to create the table in the database:
php artisan migrate
Step 3: Handling Message Persistence via WebSocket
When a user sends a message, we need to handle and persist the message into the database. In the message-sent event, you can use Laravel Broadcasting to send the message over WebSocket and simultaneously save the message in the database.
// app/Events/MessageSent.php
public function broadcastOn()
{
return new Channel('chat');
}
public function broadcastWith()
{
return [
'message' => $this->message,
'user' => $this->user,
];
}
// app/Listeners/SaveMessage.php
public function handle(MessageSent $event)
{
$message = new Message();
$message->user_id = $event->user->id;
$message->content = $event->message;
$message->save();
}
Conclusion
Integrating Laravel WebSocket with a database allows you to store and manage real-time data effectively. By combining WebSocket with a database, you can build complex real-time applications like Chat, instant notifications, and event tracking in a flexible and powerful manner.