DEV Community

Cover image for Building Real-time Notifications with Laravel Broadcasting and React

Building Real-time Notifications with Laravel Broadcasting and React

"Your users don't want to refresh to know what just happened."

Real-time notifications keep your users in sync with what's happening in your app the moment it happens. Whether it's a new club event, a gallery image, or a direct message, Laravel Broadcasting combined with React (or Firebase push) gives you a clean, scalable way to deliver these updates instantly.

This guide walks you through building real-time notifications in Laravel, wiring them to a React frontend (and optionally Firebase), and structuring everything in a way that fits enterprise-grade apps

Key Takeaways

  • Use Laravel Broadcasting for server-side event streaming over WebSockets
  • Use Laravel Echo in React to subscribe to channels and listen for events
  • Use private channels for per-user notifications and proper authorizationUse Laravel notifications when you want a unified API (database, broadcast, mail, etc.)
  • Use Firebase Cloud Messaging for OS-level push notifications on web/mobile
  • Real-time notifications improve UX, engagement, and responsiveness of your Laravel apps

Index

  1. Why Real-time Notifications Matter
  2. How Laravel Broadcasting Works
  3. Broadcasting vs Firebase Notifications
  4. Setting Up Broadcasting in Laravel
  5. Creating a Broadcastable Notification/Event
  6. Wiring React with Laravel Echo
  7. Implementing User-specific (Private) Notifications
  8. Using Firebase for Push Notifications
  9. Common Mistakes to Avoid
  10. FAQs
  11. Interesting Facts & Stats
  12. Conclusion

1. Why Real-time Notifications Matter

Real-time notifications ensure your app pushes updates to users the moment something important occurs, instead of waiting for manual refreshes or cron-based checks
This is critical for:

- Engagement: Users stay hooked when they see new events, bookings, or messages instantly
- Productivity: Admins can react faster to changes like new registrations or approvals
- UX: Your app feels modern and responsive, like chat apps or live dashboards
- Scalability: WebSockets reduce polling overhead and server load for frequent updates

Today, Laravel's built-in broadcasting API, combined with WebSockets or Pusher-style drivers, makes building these real-time experiences straightforward

2. How Laravel Broadcasting Works (The Basics)

“A real-time notification system is the heartbeat of a responsive web application.”- Technical Lead

Laravel Broadcasting lets you "broadcast" server-side events over WebSockets (or Pusher-like services) so your frontend can listen in real time.

Core pieces:

  • Broadcast events: PHP classes (often implementing ShouldBroadcast) that describe what to send to the front end
  • Channels: Named streams (public, private, or presence) your front end subscribes to
  • Broadcasters: Drivers like pusher, ably, redis + laravel-websockets, etc., that handle WebSocket delivery
  • Laravel Echo: JavaScript client that connects to your broadcaster and listens to events in the browser/React app
    Example event outline:

  • Backend: Broadcast an event (e.g., NewNotificationCreated) on channel notifications or App.Models.User.{id}

  • Frontend: Echo.channel('notifications').listen('NewNotificationCreated', callback)

  • Laravel reconstructs the payload into JSON and sends it over the WebSocket connection automatically.

3. Broadcasting vs Firebase Notifications

Both Broadcasting and Firebase deliver real-time messages, but they solve slightly different problems.

Table 1: Comparison of Laravel Broadcasting and Firebase FCM
A solid architecture often uses both: broadcasting for in-app real-time UI and FCM for OS-level push when the user is not actively on the page.

4. Setting Up Broadcasting in Laravel

Laravel ships with broadcasting out of the box; you just pick a driver and configure it.
Steps:

  • Configure broadcast driver in .env:
    • BROADCAST_DRIVER=pusher (or ably, redis, etc.)
  • Configure your broadcaster in config/broadcasting.php (keys, cluster, host, etc.)
  • Enable the BroadcastServiceProvider if not already enabled (for channels.php)
  • Define channels in routes/channels.php:
    • Public channel: Broadcast::channel('notifications', fn () => true);
    • Private channel: Broadcast::channel('App.Models.User.{id}', fn ($user, id)=>(int)user->id === (int)$id);

If you use Laravel WebSockets or a self-hosted server, you configure a pusher-compatible app ID/key/secret pointing to your WebSocket host and port.

5. Creating a Broadcastable Notification/Event

There are two main ways to broadcast from Laravel: events and notifications.
Events approach:
Generate an event:
php artisan make:event ClubEventCreated
Example:

class ClubEventCreated implements ShouldBroadcast
{
    public $clubEvent;

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

    public function broadcastOn(): array
    {
        return [
            new Channel('club-events'), // Public
            new PrivateChannel('App.Models.User.' . $this->clubEvent->user_id), // User-specific
        ];
    }

    public function broadcastWith(): array
    {
        return [
            'message' => 'New club event: ' . $this->clubEvent->name,
            'event' => $this->clubEvent,
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Dispatch: event(new ClubEventCreated($eventModel));

Notifications approach:

Use Laravel's Notification system and add broadcast to via().
Laravel automatically broadcasts a notification to a channel App.Models.User.{id}.
Example:

class NewClubEventNotification extends Notification implements ShouldBroadcast
{
    public $clubEvent;

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

    public function via($notifiable): array
    {
        return ['database', 'broadcast'];
    }

    public function toBroadcast($notifiable): BroadcastMessage
    {
        return new BroadcastMessage([
            'message' => 'New club event created!',
            'event_id' => $this->clubEvent->id,
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Send: $user->notify(new NewClubEventNotification($clubEvent));
This gives you database + real-time delivery with almost no extra wiring.

6. Wiring React with Laravel Echo

“Users shouldn’t refresh to see updates,real-time notifications should do the talking.” - Frontend Specialist

On the frontend, you use Laravel Echo plus a connector like pusher-js to subscribe to channels and listen for events in React.
Key steps:

  • Install libraries in your React app (e.g., laravel-echo and pusher-js)
  • Create a shared Echo instance (for example in a separate echo.js or service file)
  • Configure with broadcaster: 'pusher', key, wsHost, wsPort, forceTLS, etc.
  • In a React component, subscribe to channels and attach listeners in useEffect, cleaning up on unmount Example pattern:
import { useEffect } from 'react';
import Echo from 'laravel-echo'; // Your Echo instance

const NotificationsComponent = ({ userId }) => {
  useEffect(() => {
    // Public channel
    Echo.channel('club-events')
      .listen('ClubEventCreated', (e) => {
        console.log('New event:', e.message);
        // Update UI state
      });

    // Private per-user notifications
    Echo.private(`App.Models.User.${userId}`)
      .notification((notification) => {
        console.log('Personal notification:', notification.message);
        // Show toast or update badge
      });

    return () => {
      Echo.leaveChannel('club-events');
      Echo.leaveChannel(`App.Models.User.${userId}`);
    };
  }, [userId]);

  return <div>Your notifications here</div>;
};
Enter fullscreen mode Exit fullscreen mode

This pattern keeps your React code clean and focused on updating state when events arrive.

7. Implementing User-specific (Private) Notifications

For real-world apps, you rarely show the same notification to everyone; you want user-specific or role-specific notifications.
Laravel makes this easy:

  • Use private channels like App.Models.User.{id} for per-user streams
  • Write a channel authorization callback in routes/channels.php to ensure only the owner can subscribe
  • Use Laravel Notifications with broadcast channel, which automatically targets App.Models.User.{id}

Example channels.php:

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

On the React side:

  • Subscribe to Echo.private(App.Models.User.${userId}) once the user is authenticated
  • Use the .notification(...) helper to receive any broadcast notification
  • Update a notifications list, counter badge, or toast component when data arrives This maps perfectly to scenarios like "show a red dot on the bell icon when there is a new club event for this user".

8. Using Firebase for Push Notifications

Broadcasting covers in-app real-time, but sometimes you want OS-level push notifications via Firebase Cloud Messaging (FCM).
Common flow:

  • Configure a Firebase project and enable FCM
  • Include the Firebase JS SDK in your web app and request notification permission from the user
  • Retrieve and store the user's FCM token in your Laravel users table
  • From Laravel, send push notifications using FCM HTTP APIs or a package (e.g., via a notification channel)
class ClubEventPushNotification extends Notification
{
    public function via($notifiable): array
    {
        return ['fcm']; // Assuming a package like laravel-fcm
    }

    public function toFcm($notifiable)
    {
        return FcmMessage::create('New Club Event')
            ->withBody('Check out the new event!')
            ->withData(['event_id' => $this->event->id]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage examples:

  • When a new gallery image is uploaded, broadcast via Laravel for users currently on the site and send an FCM push for users in the background
  • When a booking is about to expire, trigger queued notifications that hit FCM and update in-app badges via broadcasting at the same time Combining FCM with Laravel Broadcasting gives you a full real-time story: in-tab updates plus system-level pushes.

9. Common Mistakes to Avoid

  • Mixing up event and notification names in Echo listeners (they must match the class name or notification structure)
  • Forgetting to start or configure your WebSocket server (like laravel-websockets or echo server)
  • Using public channels for sensitive data instead of private channels with authorization callbacks
  • Not cleaning up Echo subscriptions in React components, causing memory leaks or duplicate listeners
  • Ignoring token lifecycle for FCM (tokens change and need to be refreshed and updated on the backend)
  • Avoiding these issues will save you hours of debugging and strange "it works sometimes" bugs.

10. FAQs

Q. Do I need Pusher to use Laravel Broadcasting?
No. Laravel supports multiple broadcasters, including self-hosted Laravel WebSockets and Redis-based setups that emulate Pusher's protocol.

Q. When should I use events vs notifications for broadcasting?
Use broadcastable events when you just need a fire-and-forget message; use notifications when you also want database/email/SMS plus real-time broadcasting under a single API.

Q. How do I secure user-specific notifications?
Use private channels (App.Models.User.{id}) with proper channel authorization and Echo.private on the frontend.

Q. Can I use React, Vue, or plain JS with Laravel Echo?
Yes. Echo is framework-agnostic and can be used in React, Vue, Next.js, or even vanilla JavaScript, as long as you instantiate it correctly in your client-side code.

Q. Is Firebase required for real-time notifications?
No. WebSockets via Broadcasting and Echo are enough for in-app real-time updates. Firebase is only needed if you want OS-level push notifications outside of the active browser tab or app.

11. Interesting Facts & Stats

  • Laravel's broadcasting system is built to integrate directly with its event and notification APIs, so you can reuse the same infrastructure for in-app events, queues, and real-time updates.

  • Articles and tutorials on WebSockets and real-time Laravel apps highlight significant reductions in server load when replacing long polling with proper WebSocket broadcasting.

  • Guides on Laravel + Next.js and Laravel + WebSockets show that real-time notification architectures scale well when you offload to WebSockets servers and use broadcasting events efficiently.

  • Documentation for Laravel notifications emphasizes how broadcasting and the notification system together simplify multi-channel delivery (database, mail, Slack, broadcast) with minimal code.

  • Firebase FCM is widely used as a backend for mobile and web push notifications, and it integrates well with Laravel as long as you manage tokens and server keys securely.

12. Conclusion

Real-time notifications transform your Laravel app from "request-response only" to a live, interactive experience.

By combining Laravel Broadcasting, Echo, and a React frontend (plus optional Firebase), you can deliver user-specific updates instantly, keep your UI always fresh, and still maintain a clean, testable backend architecture.

References

[1] Laravel Documentation. (2025). Broadcasting. https://laravel.com/docs/12.x/broadcasting
[2] Rumpel, C. (2020). Laravel Real-Time Notifications. Retrieved from https://christoph-rumpel.com/2020/11/laravel-real-time-notifications
[3] Laravel Documentation. (2025). Notifications. https://laravel.com/docs/12.x/notifications
[4] Laravel-Docs. (2024). Event Broadcasting. Retrieved from https://laravel-docs.readthedocs.io/en/latest/broadcasting/
[5] Dev.to. (2025). Implementing Real-time Notifications Using Laravel WebSockets. Retrieved from https://dev.to/prateekshaweb/implementing-real-time-notifications-using-laravel-websockets-and-nextjs-a-complete-guide-1a2l
[6] iFlair. (2025). Real-Time Push Notifications in Laravel with Firebase. https://www.iflair.com/real-time-push-notifications-in-laravel-with-firebase/
[7] Pusher. (2024). Build Online Presence into Your Laravel App. Retrieved from https://pusher.com/tutorials/online-presence-laravel/

About the Author: Lakashya is a web developer at AddWebSolution, building scalable apps with PHP & React. Sharing ideas, code, and creativity.

Top comments (0)