Broadcasting & Real-Time Events in Laravel 11: Pusher, Laravel Echo, and WebSockets

Jayprakash Jangir
3 min readJun 13, 2024

Real-time functionality is a key feature in modern web applications. It allows for instant communication and updates, enhancing user experience and engagement. Laravel 11, with its robust broadcasting capabilities, makes implementing real-time features straightforward and efficient. This blog post will delve into broadcasting and real-time events in Laravel 11, focusing on Pusher, Laravel Echo, and WebSockets.

What is Broadcasting in Laravel?

Broadcasting in Laravel refers to the act of transmitting events from your server-side application to client-side applications in real-time. Laravel makes it easy to “broadcast” these events over a WebSocket connection. This is particularly useful for building features such as live notifications, real-time updates, chat applications, and more.

Key Components

  1. Pusher: A hosted service that simplifies the process of adding real-time data and functionality to web and mobile applications. It provides APIs for sending real-time updates via WebSockets.
  2. Laravel Echo: A JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by Laravel. It provides an expressive API for interacting with WebSockets.
  3. WebSockets: A communication protocol that provides full-duplex communication channels over a single TCP connection. It’s ideal for applications that require real-time updates.

Setting Up Broadcasting in Laravel 11

Step 1: Install Laravel

First, ensure you have Laravel 11 installed. You can create a new Laravel project using Composer:

composer create-project --prefer-dist laravel/laravel blog
cd blog

Step 2: Configure Broadcasting

Open your .env file and configure the broadcasting driver. We'll use Pusher for this example:

BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-app-key
PUSHER_APP_SECRET=your-pusher-app-secret
PUSHER_APP_CLUSTER=your-pusher-app-cluster

Next, install the Pusher PHP SDK:

composer require pusher/pusher-php-server

Step 3: Install Laravel Echo and Pusher JS

Laravel Echo and the Pusher JS library are necessary for client-side real-time updates. Install them using npm:

npm install --save laravel-echo pusher-js

Step 4: Configure Laravel Echo

Create a new JavaScript file, typically resources/js/bootstrap.js, and configure Laravel Echo:

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true
});

Ensure you have these environment variables defined in your .env file and also in your webpack.mix.js or vite.config.js:

mix.js('resources/js/app.js', 'public/js').vue()
.sass('resources/sass/app.scss', 'public/css')
.sourceMaps()
.version()
.options({
processCssUrls: false
});

mix.browserSync('your-local-dev-url.test');
mix.webpackConfig({
resolve: {
alias: {
'@': path.resolve('resources/js'),
},
},
});

Step 5: Define Broadcast Event

Create an event that you want to broadcast. For example, a NewMessage event:

php artisan make:event NewMessage

Edit the generated event class (app/Events/NewMessage.php) to implement ShouldBroadcast:

namespace App\Events;

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

Step 6: Broadcast the Event

Trigger the event in your application. For example, in a controller method:

use App\Events\NewMessage;

public function sendMessage(Request $request)
{
$message = $request->input('message');
event(new NewMessage($message));
return response()->json(['status' => 'Message sent!']);
}

Step 7: Listen for Events in Frontend

In your frontend JavaScript file, listen for the broadcasted event:

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

Step 8: Run the Application

Compile your JavaScript and run your application:

npm run dev
php artisan serve

Now, your application is set up to broadcast and receive real-time events using Laravel Echo, Pusher, and WebSockets. When a new message is sent, it will be broadcast to all clients listening on the chat channel in real-time.

Conclusion

Broadcasting and real-time events in Laravel 11 are powerful features that can significantly enhance the interactivity and responsiveness of your web applications. By leveraging Pusher, Laravel Echo, and WebSockets, you can implement real-time functionalities such as live notifications, chat systems, and more with ease.

Laravel’s elegant syntax and comprehensive documentation make it an excellent choice for modern web development. With the steps outlined in this blog post, you should be well on your way to integrating real-time features into your Laravel applications. Happy coding!

--

--