Laravel Echo is a library that makes it easy to work with WebSockets and real-time events in Laravel applications. When combined with Vue.js, you can create a seamless real-time notification system. Here's a step-by-step guide on how to use Laravel Echo with Vue.js for real-time notifications:
1. Install Necessary Packages:
Make sure you have the necessary packages installed. Install Laravel Echo, Pusher, and the Laravel Echo Vue plugin.
bashcomposer require pusher/pusher-php-server npm install --save laravel-echo pusher-js
2. Configure Pusher:
Configure Pusher by adding your Pusher credentials in the .env
file.
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
3. Configure Laravel Echo:
In your resources/js/bootstrap.js
file, import and configure Laravel Echo.
javascriptimport 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,
});
4. Broadcast Event:
Create a broadcast event that will be triggered when a notification occurs.
bashphp artisan make:event NewNotificationEvent
In the generated NewNotificationEvent
class, modify the broadcastOn
method to specify the channel.
phppublic function broadcastOn()
{
return new Channel('notifications');
}
5. Trigger Event:
In your controller or wherever you want to trigger the event, use the broadcast
method.
phpuse App\Events\NewNotificationEvent;
public function sendNotification()
{
// Your notification logic here
event(new NewNotificationEvent($notificationData));
}
6. Listen for Events in Vue Component:
In your Vue component, use Laravel Echo to listen for the event.
javascript<template>
<!-- Your component template -->
</template>
<script>
export default {
mounted() {
window.Echo.channel('notifications')
.listen('NewNotificationEvent', (event) => {
console.log('New notification received:', event);
// Handle the notification
});
}
}
</script>
7. Run Laravel Echo Server:
To enable real-time communication, you may need to run Laravel Echo Server. Install it globally:
bashnpm install -g laravel-echo-server
Configure it using:
bashlaravel-echo-server init
Run the server:
bashlaravel-echo-server start
8. Start Your Vue App:
Run your Vue.js application:
bashnpm run watch
Now, when a notification is triggered in your Laravel application, the Vue component will receive and handle the real-time event.
Note: Ensure that your server, Echo server, and Vue.js application are running concurrently. Additionally, this example uses Pusher as the broadcasting service; you can adjust the configurations if you are using a different broadcasting service.