Implementing a dynamic notification system with Laravel Echo and Vue.js involves setting up a real-time messaging system using Laravel Echo and broadcasting events. Here's a step-by-step guide to help you achieve this:
broadcasting.php
file located in the config
directory. Set the default
driver to 'pusher' or 'redis' depending on your preference.php// config/broadcasting.php
'default' => env('BROADCAST_DRIVER', 'pusher'),
// Add Pusher configuration if you choose Pusher
'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,
],
],
// Add Redis configuration if you choose Redis
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
.env
file.envBROADCAST_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_cluster # OR, if you choose Redis REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379
Create a Laravel event that will be broadcasted when a notification occurs.
bashphp artisan make:event NotificationEvent
Edit the generated NotificationEvent
class:
php// app/Events/NotificationEvent.php
class NotificationEvent implements ShouldBroadcast
{
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastOn()
{
return new Channel('notifications');
}
}
Broadcast the event when a notification occurs. You can do this in your controller, service, or wherever you generate notifications.
php// ExampleController.php
use App\Events\NotificationEvent;
public function sendNotification()
{
$message = 'New notification message';
event(new NotificationEvent($message));
return response()->json(['message' => 'Notification sent!']);
}
Set up your Vue component to listen for the notifications using Laravel Echo.
javascript// resources/js/components/NotificationComponent.vue
<template>
<div>
<ul>
<li v-for="notification in notifications" :key="notification.id">
{{ notification.message }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
notifications: [],
};
},
mounted() {
Echo.channel('notifications')
.listen('NotificationEvent', (event) => {
this.notifications.push(event);
});
},
};
</script>
Include your Vue component wherever you want to display the notifications.
html<!-- resources/views/welcome.blade.php -->
@extends('layouts.app')
@section('content')
<notification-component></notification-component>
@endsection
Make sure your Laravel application is running and Laravel Echo server is active if you're using Redis or a queue driver.
bashphp artisan serve
# Run Laravel Echo server in a separate terminal window
laravel-echo-server start
Now, when you trigger a notification in your Laravel application, it should be dynamically displayed in your Vue.js component in real-time.