Implementing a real-time notification system using Laravel Echo and Vue.js involves several steps. Laravel Echo is a library that makes it easy to implement real-time functionality with WebSockets in Laravel applications. Here's a basic guide on how you can achieve this:
Set Up Laravel Echo and Pusher:
Install Laravel Echo and Pusher:
bashcomposer require pusher/pusher-php-server npm install --save laravel-echo pusher-js
Configure your Laravel application to use Pusher. Update your .env
file with your Pusher credentials:
envBROADCAST_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
Update config/broadcasting.php
to use Pusher:
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' => true,
],
],
],
Set Up Broadcasting Events:
Create an event class for your notifications:
bashphp artisan make:event NewNotification
Update the broadcastOn
method in NewNotification
class:
phppublic function broadcastOn()
{
return new Channel('notifications');
}
Create Vue Component for Notifications:
Create a Vue component to display notifications. This can be a simple toast notification or a more complex component, depending on your needs.
vue// resources/js/components/Notification.vue <template> <div v-if="notification"> {{ notification.message }} </div> </template> <script> export default { data() { return { notification: null, }; }, mounted() { window.Echo.channel('notifications').listen('NewNotification', (event) => { this.notification = event; }); }, }; </script>
Include Vue Component in Blade File:
Include your Vue component in your Blade file:
blade<!-- resources/views/welcome.blade.php --> <!DOCTYPE html> <html> <head> <!-- Other head elements --> <script src="{{ asset('js/app.js') }}" defer></script> </head> <body> <!-- Your content --> <notification></notification> </body> </html>
Broadcast the Event:
In your controller or wherever you want to send a notification, broadcast the event:
phpuse App\Events\NewNotification;
public function sendNotification()
{
event(new NewNotification('New notification message'));
}
This will trigger the NewNotification
event, and the Vue component will receive and display the notification.
Run Laravel Echo Server (Optional):
If you are not using Laravel Echo Server, you can run the following command to listen for events:
bashphp artisan queue:listen --tries=1
Alternatively, you can use Laravel Echo Server for better scalability in production.
That's a basic setup for a real-time notification system using Laravel Echo and Vue.js. Make sure to customize it according to your specific needs.