Support the ongoing development of Laravel.io →
Article Hero Image

Getting started with Laravel Reverb and Livewire

15 Apr, 2024 4 min read

Photo by Gontran Isnard on Unsplash

In the beginning of March (2024) Laravel reverb was released. Now it's officially released and go through a small example in this tutorial.

What is Laravel Reverb

Laravel reverb, is a first-party WebSocket server for Laravel applications. Which basically let's you run a websocket server with your app. The Laravel team announced it at Laracon EU in february 2024, and I must say the example Joe Dixon showcased on stage blew me away.

Installing Reverb

Installing reverb is made easy for us. It's one of the options when we install broadcasting in our laravel 11 application. After we run php artisan install:broadcasting we'll be prompted with the question if we'd like to use Reverb for broadcasting This command will create the needed configuration file for broadcasting. It will also create a channel routes file.

Besides that it wil add echo to our vite setup and generate the needed environment variables.

Set up our Livewire component

For the ease of this tutorial we'll use Livewire to play around with reverb. We'll install Livewire with composer require livewire/livewire.

A livewire component will be needed to provide the needed functionality so we'll generate that with this artisan command php artisan make:livewire MessagesComponent. This will generate a component class and a blade file that goes with it.

In the component file we should create a message variable and an action to capture the entered message, for now, later on, we'll dispatch the event in that action.

class MessageComponent extends Component
{
    public $message = "";
    
    public function submitMessage(){
        dd($this->message);
    }

    public function render()
    {
        return view('livewire.message-component');
    }
}

For now we'll only dump & die the message. In our blade file we should provide the input and button to perform the action.

<div>
    <input wire:model='message' type="text">
    <button wire:click='submitMessage'>Submit</button>
</div>

Creating an event

Once we have our basic setup ready we should create our event with php artisan make:event MessageEvent. This will generate an event for us with the given name. We adjust the event to our needs, starting with making it implement ShouldBroadcast or ShouldBroadcastNow. In this tutorial we'll be using ShouldBroadcastNow, because we want our event to be broadcasted right away, we won't be using a Queue to handle this.

We'll also need a public property 'theMessage', and adjust the channel to use a normal Channel instead of a PrivateChannel in the BroadcastOn function.

Here is what our event should look like:

class MessageEvent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public string $theMessage;
    /**
     * Create a new event instance.
     */
    public function __construct($incomingMessage)
    {
        //
        $this->theMessage = $incomingMessage;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return [
            new Channel('our-channel'),
        ];
    }
}

Glueing it all together

Now that we have set up our Livewire component and created our event, it's time to glue it together.

To store all messages we'll use an array in our component in this tutorial. In real life you should store the messages in a database, where it won't get lost on refresh. But in this tutorial we're using an array just to test the reverb functionality. So we'll create a public property conversation which is an array.

In our submitMessage function we'll dispatch the event with the entered message. Thanks to the adjustments we've made in the event, it will be dispatched on the required channel with the message inside as it's data.

Now we need to listen for that event. We'll create a function listenForMessage which accepts data. In this function we'll add the message (that's inside of the event's data object) to our conversation array. To listen for the event on the our-channel channel we'll be using echo. We'll be using a Livewire Attribute to do so, basically we must tell it to listen using 'On' the 'our-channel' channel for the 'MessageEvent' using 'Echo'. This results in the following attribute #[On('echo:our-channel,MessageEvent')].

Our Livewire component should look like this after these adjustments.

class MessageComponent extends Component
{
    public $message = "";
    public $conversation = [];
    
    public function submitMessage(){
        MessageEvent::dispatch($this->message);
    }

    #[On('echo:our-channel,MessageEvent')]
    public function listenForMessage($data){
       $this->conversation[] = $data['theMessage'];
    }
    
    public function render()
    {
        return view('livewire.message-component');
    }
}

You'll notice that we are also using the listenForMessage function to store the message we've sent ourselves. This eases out the code an just looks better 🙂

Running the reverb server and test out

Now it's time to start our reverb server and start sending messages. Starting the reverb server can be started with php artisan reverb:start, you could chain --debug on to that to see the messages that reverb handles for us.

And that's it, we can now send messages in real time from one instance of the app an immediately see the message we've sent on all connected instances, including our own conversation array.

Conclusion

With reverb we are able to run our very own websocket server inside of our Laravel application. With just a few commands this is made easy for us developers. We at Vulpo will be using this for use in a few client applications and internal projects.

Now go and play around with it! Happy coding! ✌️

Last updated 3 weeks ago.

driesvints liked this article

1
Like this article? Let the author know and give them a clap!

Other articles you might like

Article Hero Image November 18th 2024

Laravel Custom Query Builders Over Scopes

Hello 👋 Alright, let's talk about Query Scopes. They're awesome, they make queries much easier to r...

Read article
Article Hero Image November 19th 2024

Access Laravel before and after running Pest tests

How to access the Laravel ecosystem by simulating the beforeAll and afterAll methods in a Pest test....

Read article
Article Hero Image November 11th 2024

🍣 Sushi — Your Eloquent model driver for other data sources

In Laravel projects, we usually store data in databases, create tables, and run migrations. But not...

Read article

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.