Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Broadcasting with WebSockets Tutorial

Introduction

Broadcasting with WebSockets enables real-time communication between clients and servers. It is particularly useful for applications that require instant updates, such as chat applications, live notifications, and collaborative tools. In this tutorial, we will walk through the process of setting up WebSockets in a Laravel application to broadcast events to connected clients.

Prerequisites

Before we begin, ensure you have the following:

  • Basic knowledge of Laravel and PHP.
  • Laravel installed on your machine.
  • A working database connection configured in your Laravel application.

Step 1: Install Laravel Echo and Socket.IO

First, we need to install Laravel Echo and Socket.IO. Laravel Echo is a JavaScript library that makes it easy to work with WebSockets in Laravel applications. You can install it using npm:

npm install --save laravel-echo socket.io-client

This command will add both Laravel Echo and Socket.IO to your project.

Step 2: Configure Broadcasting in Laravel

Open the config/broadcasting.php file in your Laravel application. You need to set the default driver to pusher, which is the recommended way to use WebSockets in Laravel.

'default' => env('BROADCAST_DRIVER', 'pusher')

Next, you will need to set your Pusher credentials in your .env file:

BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your_app_id
PUSHER_APP_KEY=your_app_key
PUSHER_APP_SECRET=your_app_secret
PUSHER_APP_CLUSTER=your_app_cluster

Step 3: Create an Event

Now, let's create an event that we will broadcast. You can create an event using the Artisan command:

php artisan make:event MessageSent

Open the newly created event class app/Events/MessageSent.php and implement the ShouldBroadcast interface:

namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MessageSent implements ShouldBroadcast {
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct($message) {
$this->message = $message;
}
public function broadcastOn() {
return new Channel('chat');
}
}

Step 4: Broadcasting the Event

You can now broadcast the event from your controller. Here’s how you can do that:

use App\Events\MessageSent;
public function sendMessage(Request $request) {
$message = $request->input('message');
broadcast(new MessageSent($message));
return response()->json(['status' => 'Message Sent!']);
}

Step 5: Listening to Broadcasts on the Client Side

Now that we have set up the backend, let’s listen for the broadcasts on the client side. In your JavaScript file, use the following code to listen for the MessageSent event:

window.Echo.channel('chat')
.listen('MessageSent', (e) => {
console.log(e.message);
});

This code will log the received message to the console whenever a message is sent.

Conclusion

In this tutorial, we have learned how to set up broadcasting with WebSockets in a Laravel application. We covered installing necessary packages, configuring broadcasting, creating events, and listening for broadcasts on the client side. This powerful feature can enhance your applications by providing real-time updates and interactions.