To implement real-time updates for your notification bell using Laravel Echo and Pusher, you'll need to follow these steps:
-
Install and Configure Laravel Echo and Pusher: First, make sure you have Laravel Echo and Pusher installed and configured in your Laravel application.
npm install --save laravel-echo pusher-jsIn your
resources/js/bootstrap.jsfile, uncomment or 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, encrypted: true });Make sure to set the appropriate Pusher keys and cluster in your
.envfile. -
Broadcast Events: Ensure that your event class implements
ShouldBroadcastand is set up correctly to broadcast on a channel.use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class NewUserEnquiryEvent implements ShouldBroadcast { // Event content here public function broadcastOn() { return new Channel('notifications'); } } -
Listen for Events in Vue Component: In your Vue component, you'll need to listen for the event using Laravel Echo. Here's an example of how you might do this:
<script> export default { data() { return { notifications: [], unreadCount: 0 }; }, mounted() { this.listenForNotifications(); }, methods: { listenForNotifications() { Echo.channel('notifications') .listen('NewUserEnquiryEvent', (event) => { this.notifications.push(event.notification); this.unreadCount++; }); }, markAsRead(notificationId) { // Logic to mark notification as read // Update unreadCount accordingly } } } </script> -
Update Your Blade Template: In your Blade template, you'll need to include the Vue component and pass any initial data it might need.
<notifications-component :initial-notifications="{{ $notifications }}" :initial-unread-count="{{ $unreadCount }}"></notifications-component> -
Handle Authentication (Optional): If you need to restrict the channel to authenticated users, you can use private channels and modify your
broadcastOnmethod to return aPrivateChannelinstance.public function broadcastOn() { return new PrivateChannel('notifications.' . $this->user->id); }And in your
channels.phpfile, define the authorization logic for the private channel:Broadcast::channel('notifications.{userId}', function ($user, $userId) { return (int) $user->id === (int) $userId; });Then, in your Vue component, subscribe to the private channel:
Echo.private('notifications.' + userId) .listen(...)
Remember to compile your JavaScript assets with npm run dev or npm run production after making changes to your JavaScript files.
This should give you a real-time notification system where the notification count and dropdown are updated without needing to refresh the page.