Implement real-time notifications in a Laravel and React application using Pusher.
Photo by Mohammad Rahmani on Unsplash
Set Up Laravel Project: Start by creating a new Laravel project if you haven't already:
laravel new laravel-react-push-notification
Install Pusher Package: Laravel provides an excellent package for Pusher integration out of the box. Install it via Composer:
composer require pusher/pusher-php-server
Set Up Pusher Account: Sign up for a free account on Pusher if you don't have one already. Once logged in, create a new app and note down the credentials (app id, key, secret).
Configure Pusher: Update your
.env
file with your Pusher credentials:BROADCAST_DRIVER=pusher PUSHER_APP_ID=your_pusher_app_id PUSHER_APP_KEY=your_pusher_app_key PUSHER_APP_SECRET=your_pusher_app_secret PUSHER_APP_CLUSTER=your_pusher_app_cluster
Create Notification: Generate a notification using Laravel's artisan command:
php artisan make:notification NewNotification
Broadcast Notification: Modify the
NewNotification
class to broadcast the notification using Pusher:public function via($notifiable) { return ['broadcast']; } public function toBroadcast($notifiable) { return new BroadcastMessage([ 'message' => 'This is a real-time notification!', ]); }
Set Up React: Set up your React application within the Laravel project or separately. Ensure that you have Pusher's JavaScript library installed.
Subscribe to Pusher Channel: In your React application, subscribe to the Pusher channel where Laravel broadcasts notifications.
Handle Notifications in React: When a notification is received in your React application, display it to the user.
Test: Test your application to ensure that notifications are being broadcasted from Laravel and received in your React application in real-time.
Here's a simple example of how you can subscribe to a Pusher channel and handle notifications in React:
import { useEffect, useState } from 'react'; import Pusher from 'pusher-js'; const NotificationComponent = () => { const [notifications, setNotifications] = useState([]); useEffect(() => { const pusher = new Pusher('YOUR_PUSHER_KEY', { cluster: 'YOUR_PUSHER_CLUSTER', encrypted: true, }); const channel = pusher.subscribe('notifications'); channel.bind('App\\Events\\NewNotification', data => { setNotifications(prevNotifications => [...prevNotifications, data.message]); }); return () => { channel.unbind_all(); channel.unsubscribe(); }; }, []); return ( <div> <h2>Notifications</h2> <ul> {notifications.map((notification, index) => ( <li key={index}>{notification}</li> ))} </ul> </div> ); }; export default NotificationComponent;
Remember to replace 'YOUR_PUSHER_KEY'
and 'YOUR_PUSHER_CLUSTER'
with your actual Pusher credentials.
This should give you a basic setup for implementing real-time notifications in your Laravel and React application using Pusher. Make sure to adjust the code according to your specific requirements and application structure.