Laravel Websockets

In the current project I just started, a live display needs to be implemented for meal registration for students, teachers and others: The person scans a QR code, for the meal serving it has to show immediately on a screen, which meal has to be prepared. For this I now use Laravel Websockets. This article describes in short the installation up to the exemplary use.

You need 3 things to be installed:

bootstrap.js

app.js

In this first step I do not use TLS encryption yet.

Now I add a component, I name it TestUser.vue; registering the component in the app.js file:

TestUser.vue

This is just a testing component without greater sense, it mainly should demonstrate the functionality

This component receives a user as the event argument e, where it takes the first and the last name and pushes them as an object to the names array. This event is called, if a person scans its QR code represanting a selected dish.

In the template, I iterate over this names array and display the names.

This results in a screen display like the following:

Now let’s move on to the server part of this: First you have to create an event:

In the constructor, the user model should be passed by as public property, because then it’s sent along with the broadcasting event to the client:

The second thing is to implement the ShouldBroadcast interface, or – if you don’t want this event to be queued – the ShouldBroadcastNow interface. In my case, the name of the person, who scanned the QR code should immediatley appear on the screen, so I used

And the third thing is to specify the channel. In my case I use a public channel for simplicity sake (a bit later I will work on the security – now it’s all about getting this up and running successfully…)

The name of the channel add-user has to be the same as specified in the vue component in the .channel method. And the name specified in the .listen method AddRandomUserEvent is the events name.

Allright, let’s get the websocket server running…

…and load the client page. Even if the clients page is already opened, the websocket server should accept the connection:

Well, and then go dispatch the event – in my case I simulate 100 QR Code scans with only very little delay with this loop

Well played, Laravel && laravel-websockets!