Laravel Reverb
Laravel Reverb is one of the newest additions to the Laravel ecosystem, this first-party package allows an application to communicate in real time between client and server.
An Overview
If you’ve ever come across websockets in the Laravel ecosystem before Reverb you’d most likely be using a third-party service, the most popular i’ve seen and used in the past being Pusher. With Laravel Reverb you no longer have to rely on third-party services to use WebSockets with Laravel, you can now seamlessly integrate webhooks which can utilise other parts of the Laravel ecosystem like Laravel Echo and easy deployment with Laravel Forge.
How it Works
Laravel Reverb can be used by installing broadcasting using php artisan install:broadcasting
command, this will then prompt you if you would like to install Laravel Reverb. Once it’s installed there should be some Reverb credentials that have now been generated in the .env
file and a Reverb config file at config/reverb.php
. With the integration of Laravel Broadcasting we can use Laravel Events to broadcast onto a channel. It’s possible to create either public or private channels, public channels are available to everyone but private channels can be scoped to certain users. To broadcast on a public channel we can define a channel using the broadcastOn
method in an event
use Illuminate\Broadcasting\Channel;
public function broadcastOn(): Channel
{
return new Channel('my-public-channel');
}
To define a private channel we do exactly the same thing but rather than defining new Channel
we define new PrivateChannel
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
public function broadcastOn(): Channel
{
return new PrivateChannel('users.'.$this->user->id.'.export');
}
Then we can utilise Laravel Echo to listen to the websockets being broadcast from the event on the client side. To listen for the event we first define the channel we’re listening for, from the public example above that would be my-public-channel
, we then define what event we want to listen to which will use the class name of the event you want to broadcast from, for this example I will just call the event class PublicNotificationEvent
window.Echo.channel('my-public-channel')
.listen('PublicNotificationEvent', (e) => {
// When event is received execute the code here
});
If there are any public
properties defined in the event class, these will be available through the callback parameter, e
in the example above.
Integrating With Laravel Forge
It’s very easy and simple to install Laravel Reverb on a server using Laravel Forge. All you need to do is navigate to your site from the Sites
dropdown, make sure Application
is selected in the left sidebar and under Laravel
there is a toggle to activate Laravel Reverb, just toggle that on and you’re away! Just make sure your queue is set up correctly and take a read of using Laravel Reverb in production and it should seamlessly work on your site.