Implementing Real-Time Notifications in Laravel Using WebSockets

28 Jan 2025 07:56 PM

Real-time notifications have become a crucial feature for modern web applications, enhancing user experience by delivering instant updates. Laravel provides robust tools to integrate real-time functionalities easily. In this detailed step-by-step guide, we’ll cover how to implement real-time notifications in Laravel using WebSockets, Laravel Echo, and Pusher.

Step 1: Install Laravel Echo and Pusher

Laravel Echo works seamlessly with Pusher to enable real-time capabilities.

  1. Open your terminal and run the following command to install Laravel Echo and Pusher JavaScript libraries:

    npm install --save laravel-echo pusher-js
    
  2. Ensure Node.js and npm are installed on your system to execute the above command.

Step 2: Set Up a Pusher Account

  1. Visit Pusher and create an account if you don’t already have one.
  2. In the Pusher dashboard:
    • Create a new application.
    • Select your cluster region (e.g., mt1, ap2, etc.).
    • Copy the App ID, Key, Secret, and Cluster from your Pusher app.

Step 3: Configure Laravel for Broadcasting

  1. Open your Laravel project and edit the .env file to add Pusher credentials:

    BROADCAST_DRIVER=pusher
    
    PUSHER_APP_ID=your-app-id
    PUSHER_APP_KEY=your-app-key
    PUSHER_APP_SECRET=your-app-secret
    PUSHER_APP_CLUSTER=your-app-cluster
    
  2. Update the broadcasting configuration file (config/broadcasting.php) to ensure Pusher is set up:

    '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'),
                'useTLS' => true,
            ],
        ],
    ],
    
  3. Run the following command to clear the configuration cache:

    php artisan config:cache
    

Step 4: Create a Notification

Laravel has a powerful notification system, which we’ll use to send real-time updates.

  1. Generate a notification class using the Artisan command:

    php artisan make:notification RealTimeNotification
    
  2.  Open the newly created file (app/Notifications/RealTimeNotification.php) and customize it:
    use Illuminate\Bus\Queueable;
    use Illuminate\Notifications\Notification;
    use Illuminate\Notifications\Messages\BroadcastMessage;
    
    class RealTimeNotification extends Notification
    {
        use Queueable;
    
        private $message;
    
        public function __construct($message)
        {
            $this->message = $message;
        }
    
        public function via($notifiable)
        {
            return ['broadcast', 'database'];
        }
    
        public function toArray($notifiable)
        {
            return [
                'message' => $this->message,
            ];
        }
    
        public function toBroadcast($notifiable)
        {
            return new BroadcastMessage([
                'message' => $this->message,
            ]);
        }
    }
    
  3. This notification uses the broadcast channel to send data over WebSockets and the database channel to store the notification in the database.

Step 5: Set Up a Broadcast Event

Laravel events enable broadcasting data to the frontend.

  1. Generate an event class:

    php artisan make:event NotificationSent
    
  2.  Open app/Events/NotificationSent.php and configure it:
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Broadcasting\Channel;
    use Illuminate\Queue\SerializesModels;
    
    class NotificationSent
    {
        use InteractsWithSockets, SerializesModels;
    
        public $message;
    
        public function __construct($message)
        {
            $this->message = $message;
        }
    
        public function broadcastOn()
        {
            return new Channel('notifications');
        }
    }
    
    This event broadcasts messages on the notifications channel.

Step 6: Integrate Laravel Echo on the Frontend

  1. Open resources/js/bootstrap.js and add the following configuration:

    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: true
    });
    
  2. Use Laravel Echo to listen for the NotificationSent event:
    window.Echo.channel('notifications')
        .listen('NotificationSent', (event) => {
            console.log('New Notification:', event.message);
        });
    
  3. Compile the frontend assets:
    npm run dev
    

Step 7: Dispatch Notifications

Now, you’re ready to test the setup.

  1. Dispatch a notification in your application. For example, from a controller:

    use App\Notifications\RealTimeNotification;
    
    $user = User::find(1); // Replace with a valid user ID
    $user->notify(new RealTimeNotification('This is a test notification!'));
    
  2. You should see the notification appear in real-time on the frontend if everything is configured correctly.

Step 8: Test and Debug

  1. Test notifications in different scenarios (e.g., new message, comment, or user action).
  2. Use the browser console and Laravel logs for debugging.

Conclusion

By following this step-by-step guide, you’ve implemented real-time notifications in Laravel using WebSockets, Pusher, and Laravel Echo. This setup ensures instant updates, making your web application more interactive and engaging for users.

1
18