Laravel 9 Real Time Notification With Laravel Web Socket

Hello Artisan,

In this Laravel WebSocket notification example tutorial, I will show you how we can setup beyondcode/laravel-websockets to make our own web socket server and can send laravel real time notification websocket. We can use pusher or other third parties to send real time data in Laravel. 

Previously I created one or more than one tutorials on real time notification in Laravel with pusher. But in this Laravel broadcasting tutorial, I will use beyondcode/laravel-websockets packages. In this package, we do not need any pusher credentials.

I will use pure vanilla js to show real-time data. If you are searching laravel WebSocket example tutorial, then this tutorial is going to be the perfect example for you. I will show you step by step setup.

What we are going to make in this tutorial:

  • Sending/broadcasting notifications from our Laravel application
  • A WebSockets server that receives those notifications
  • Our front-end that listens to the WebSockets server

 

Step 1 : Install Laravel  9

I am going to start from scratch. So download a fresh Laravel application by the following command:

composer create-project --prefer-dist laravel/laravel web-socket

 

Read also: Laravel Event Broadcasting Using Socket.io with Redis

 

Step 2: Install Web Socket

Now install web socket packages. Visit this URL to see the documentation

composer require beyondcode/laravel-websockets

 

We also need a package by Pusher but we won't use pusher credentials.

composer require pusher/pusher-php-server

 

Now update the .env like below:

.env

BROADCAST_DRIVER=pusher

//pusher credentials
PUSHER_APP_ID=AnyID
PUSHER_APP_KEY=AnyKey
PUSHER_APP_SECRET=AnySecret
PUSHER_APP_CLUSTER=mt1

 

This WebSocket server package comes with a migration to store statistic information while running your WebSocket server. You can publish the migration file using:

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"

 

Now run migrate command:

php artisan migrate

 

And here, we publish the config file of Laravel Websockets.

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

 

Now start Laravel web socket server

php artisan websockets:serve

 

Now visit the following URL:

 

web socket server
http://127.0.0.1:8000/laravel-websockets

 

Then you will see the following out

laravel-websocket-server

 

Now hit the connect button and you will see the real time statistics. 

 

Step 3: Create Event

There are two ways that we can send messages from our backend to the WebSockets server:

  • Laravel Events
  • Laravel Notifications

 

Read also: Real Time Chat App with Laravel 7.x Vue Js and Pusher

 

In this example, I just show you how to subscribe to a channel and then see real time data with laravel web socket. So create an example event like:

php artisan make:event RealTimeMessage

 

Now update the file like:

app\Events\RealTimeMessage.php

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 RealTimeMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn(): Channel
    {
        return new Channel('events');
    }
}

 

Keep remember, we have to implements our class with the ShouldBroadcast interface. Before we can try sending this event, please adapt your broadcasting.php config file to use the following options:

config/broadcasting.php

'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'),
                'useTLS' => true,
                'encrypted' => false,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'http'
            ],
],

 

Now go to your config/app.php file and uncomment the BroadcastServiceProvider.php 

'providers' => [
  App\Providers\BroadcastServiceProvider::class,
],

 

Step 4: Create Route

In this step, we will create a route to listen to our channel from server to client.

routes/web.php

use App\Events\RealTimeMessage;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    event(new RealTimeMessage('Hello World'));
    return  view('welcome');
});

 

Step 5: Listen To Messages From Our Front-end

We have to make sure that our sent event is broadcasted to the WebSockets server. We are going to use the JavaScript library Laravel Echo for that purpose. So install it by the following command:

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

 

Now uncomment the below line and update it like:

resouces/js/bootstrap.js

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,
});

 

Now run npm run dev and update the welcome file like:

resources/views/welcome.blade.php

 

Now if you visit the URL of the WebSocket server, then you will see our data, and our channel is subscribed:

We are set to go. Just open two browsers and visit the URL below and you will see the magic. Our data is broadcasted from our events channel.

 

url
http://127.0.0.1:8000/

 

Read also: How to Create Socket.io Server with Express Js in Laravel

 

Hope it can help you.

 

#laravel #laravel-9x #laravel-echo #broadcasting