Laravel Broadcast using Pusher

As usual, I was late to understand what these things could offer other than using for chat message, turns out it gives you the ability to give you something more than just pushing message. In real implementation was I needed to give feedback when the job is done.

PUSHER

create an app in pusher.com then get the credential

composer require pusher/pusher-php-server "~3.0"
app_id = "****"
key = "***********"
secret = "**********"
cluster = "ap1"

put in .env

BROADCAST_DRIVER=pusher
PUSHER_APP_ID=*****
PUSHER_APP_KEY=*****
PUSHER_APP_SECRET=*****
PUSHER_APP_CLUSTER=ap1

Uncomment - config/app.php

App\Providers\BroadcastServiceProvider::class,

Example Event - EventService Provider

'App\Events\JobFinishedEvent' => [
	'App\Listeners\JobFinishedListener',
],
php artisan event:generate

In your JobFinishedEvent add ShouldBroadcastclass

class JobFinishedEvent implements ShouldBroadcast

Route Channel.php

Broadcast::channel('job-finished-channel', function () {    
	return true;
});

Laravel Echo

Laravel Echo is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by Laravel.

assets/js/bootstrap.js then add pusher key

import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({    
	broadcaster: 'pusher',    
	key: '****',    
	cluster: 'ap1',    
	encrypted: true
});

assets/js/app.js add this

const app = new Vue({    
	el: '#app',    
	created() {      
		Echo.private('job-finished-channel')      
			.listen('JobFinishedEvent', (e) => {        
				alert('it works');      
			});    
}});

Dont forget the id="app" where you want to add the app

Broadcast::channel('job-finished-channel', function () {    
	return true;
});

To make it work add event anywhere you want

event(new JobFinishedEvent());