Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hamzaqureshi16's avatar

Real Time notifications with Inertia, React and Websockets,Pusher

So I'm making my first large application using Inertia, Laravel and ReactJS, and now I want to implement real time notifications in it. I followed many tutorial but none of them worked. I was successful in getting this in the Websockets statistics page when an event was triggered from the backend. api-message Channel: events, Event: App\Events\RealTimeMessage 09:39:48 This is my broadcasting.php

    'connections' => [

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

RealTimeMessage.php


namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;

class RealTimeMessage implements ShouldBroadcast
{
    use SerializesModels;

    public string $message;

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

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

event triggering

        // $user = User::where('referral_token', $token)->first();
        // Notification::send($user, new newNotification('New notification message'));
    
        // $pusher = new Pusher(
        //     env('PUSHER_APP_KEY'),
        //     env('PUSHER_APP_SECRET'),
        //     env('PUSHER_APP_ID'),
        //     [
        //         'cluster' => env('PUSHER_APP_CLUSTER'),
        //         'useTLS' => true,
        //     ]
        // );
    
        // $pusher->trigger('my-channel', 'my-event', ['message' => 'Hello, Pusher!']);
        event(new App\Events\RealTimeMessage('Hello World! I am an event 😄'));
        return redirect()->route('default', ['token' => $token]);
    })->name('register.token');

channels.php

<?php

use Illuminate\Support\Facades\Broadcast;

/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/

Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

bootstrap.js

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

import axios from 'axios';
window.axios = axios;

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

import Echo from 'laravel-echo';

import Pusher from 'pusher-js';
window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
    wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
    wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
    wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
    forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});

app.jsx

import './bootstrap';
import '../css/app.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import '@fortawesome/fontawesome-free/css/all.min.css';
import React from 'react';
import { createRoot } from 'react-dom';
import { createInertiaApp } from '@inertiajs/react';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import OurRegister from './Pages/Auth/OurRegister';
import OurLogin from './Pages/Auth/OurLogin';
import OurDashboard from './Pages/OurDashboard'
import EditProfile from './Pages/EditProfile';
import Help from './Pages/Help';
import Profile from './Pages/profile';
import Referral from './Pages/Referral';
import ResearchPortal from './Pages/ResearchPortal';
import ResearchPortalArticle from './Pages/ResearchPortalArticle';
import SignalPortal from './Pages/SignalPortal';
import Subscription from './Pages/Subscription';
import ForgotPassword from './Pages/Auth/ForgotPassword';
import Test from './Pages/Test';
import Tst from './Pages/tst'

import { InertiaApp } from '@inertiajs/inertia-react';

const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';

createInertiaApp({
  title: (title) => `${title} - ${appName}`,
  resolve: (name) => resolvePageComponent(`./Pages/${name}.jsx`, import.meta.globEager('./Pages/**/*.jsx')),
  setup({ el, App, props }) {
    const root = createRoot(el);

    root.render(
    //  <BrowserRouter>
        
    //     <Routes>
          
    //       <Route path="/test" element={<Test />} />
    //       <Route path="/tst" element={<Tst />} />
    //     </Routes>
    //  </BrowserRouter>
          
      <BrowserRouter>
        <App {...props} />
         <Routes>
           <Route path="/" element={<OurRegister token={props.initialPage.props.token}  />} />
           <Route path="/login" element={<OurLogin />} />
           <Route path='/forgotpassword' element={<ForgotPassword/>}/>
           {/* <Route path='/dashboard' index element={<OurDashboard/>}/> */}
             {/* <Route path='/editprofile' element={<EditProfile/>}/>
             <Route path='/help' element={<Help/>}/>
             <Route path='/profile' element={<Profile/>}/>
             <Route path='/referral' element={<Referral/>}/>
             <Route path='/researchportal' element={<ResearchPortal/>}/>
             <Route path='/researchportalarticle' element={<ResearchPortalArticle/>}/>
             <Route path='/signalportal' element={<SignalPortal/>}/>
             <Route path='/subscription' element={<Subscription/>}/>
             <Route path='/forgotpassword' element={<ForgotPassword/>}/>
             <Route path='/article' element={<ResearchPortalArticle/>}/> */}
             {/* <Route path='/test' element={<Test/>}/> */}
         </Routes>
       </BrowserRouter>  
  
    );
  },
  progress: {
    color: '#4B5563',
  },
});

I'm listening to the event in frontpage.jsx

 useEffect(() => {
    
    console.log(Echo)
    window.Echo.channel('events')
    .listen('RealTimeMessage', (e) => console.log('RealTimeMessage: ' + e.message));
  }, []);
0 likes
0 replies

Please or to participate in this conversation.