Real time with laravel-websockets

Laravel is the most popular php framework and rightfully so. Using laravel and it’s MVC model to create a simple blog or web app is very easy to learn and intuitive in nature. But how to implement a real time, live-updating user interface in laravel. That’s where laravel-websockets comes in.

Photo by Pavan Trikutam on Unsplash

In order to work with real time projects in laravel you have to have a basic knowledge of broadcasting and events.

Step 0-

Let’s start with a fresh installation of laravel. Also setup and configure database for the application.

laravel new laradiycd laradiy

Step 1-

Now let’s install laravel-websockets. You can follow their official documentation for detailed info or run the following commands.

composer require beyondcode/laravel-websocketsphp artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"php artisan migratephp artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

Step 2-

Now we have to make some changes in the application. For broadcasting event laravel-websockets uses pusher and it’s api. Pusher provides an excellent and friendly choice for real time technology for reasonable price.

// remove this line
// add these line
PUSHER_APP_ID=12345 // random numbersPUSHER_APP_KEY=QWERTY // random stringPUSHER_APP_SECRET=ASDFGH // random string

What we did is changed broadcast driver to pusher and gave some random value to identify the pusher server. The data or event we are going to send won’t go to pusher server but will go to laravel-websockets server, which is our own server.

php artisan servephp artisan websockets:serve

Go to localhost:8000, you will see laravel boilerplate app. Now go to localhost:8000/laravel-websockets, you will see the laravel-websockets dashboard. Click on connect and you will notice the some events. Voila your server is ready to listen for events. Now let’s send an event to our server.

Step 3-

Now our server is ready and in order to broadcast events let’s install pusher.

composer require pusher/pusher-php-server "^5.0"

Now we have to configer file so that the events gets sent to our own server at localhost:8000/laravel-websockets.

'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'host' => '',
'port' => 6001,
'scheme' => 'http'

Step 4-

Now to check if it’s working let’s create and send an event.

php artisan make:event NewEvent

In modify the new event class-

class NewEvent implements ShouldBroadcast{  use Dispatchable, InteractsWithSockets, SerializesModels;  public $msg;  public function __construct($msg)  {    $this->msg = $msg;  }  public function broadcastOn()  {    return new Channel('home');  }}

What we did is just added to brodcast the event. The event will accept a string parameter. Run . In the tinker terminal create an instance of -

event(new App\Events\NewEvent('hello'))

If you go to your laravel-websocket dashboard you will see the event.

NewEvent triggered.

So, now your server is running and it is listening for any event triggered. Now let’s propagate the event and to the client side with laravel-echo.

Step 5-

In order to listen for the events we need laravel-echo. Also as we are using pusher for broadcasting we need pusher-js. Let’s install those.

npm install --save-dev laravel-echo pusher-js

Now we have to configure laravel-echo in .

import Echo from 'laravel-echo';window.Pusher = require('pusher-js');window.Echo = new Echo({  broadcaster: 'pusher',  key: process.env.MIX_PUSHER_APP_KEY,  cluster: process.env.MIX_PUSHER_APP_CLUSTER,  forceTLS: false,  wsHost: window.location.hostname,  wsPort: 6001});

Most of the lines are already there just un-comment it and add wsHost and wsPort details. Compile the changed js by-

npm run dev

Step 6-

Alright everything set let’s view it in browser.

<script src="{{ asset('js/app.js') }}"></script><script>'home').listen('NewEvent', (e) => {    console.log(e.msg);  })</script>

So, we are using app.js. As we have access to Echo, we are listening for event in the channel. When that event gets triggered we will log the msg that was sent with the event. Run In tinker again trigger the event.

event(new App\Events\NewEvent('hello'))

You will see hello printed in the console window of localhost:8000.

Check the console window.

In general writing javascript in blade component is not a good idea. So, you should write the javascript code in your . In order to use echo just add before the lines. For eg.-'home').listen('NewEvent', (e) => {console.log(e.msg);});

And then compile your javascript by -

npm run dev

This should work just as fine.

So this is how you can setup laravel-echo for real time application in laravel. You can also use with laravel but with laravel-websockets you don’t need to dive in other technologies beside php. To learn more about this topic you can go through the following links-

Resources -

Homegrown Alligator

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store