1. Define EVENT and its LISTENER in App\Providers\EventServiceProvider.php
protected $listen = [
‘App\Events\TaskEvent’ => [
‘App\Listeners\TaskEventListener’,
‘App\Listeners\TaskEventListener2’, // for multiple listener
],
];
2. Generate both event and listener using php artisan as:
php artisan generate:event
3. Define created TaskEvent
– first data will come through constructor
– create public data and assign through constructor
– such data will automatically broadcast through ‘channel-name’ and ‘event-name’
– channel name and event name is declared on broadcastOn() and broadcastAs() method respectively
– By default event-name is used as its class name if not used
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
public function broadcastAs(){
return 'event-name';
}
4. Created TaskEvent class must implements ShouldBroadcast as "TaskEvent implements ShouldBroadcast"
5. After step 3 … its listener will automatically gets the value and works as specified.
6. For broadcasting we don’t need listener
7. Uncomment follwing in project\config\app.php as:
// App\Providers\BroadcastServiceProvider::class
,
7. Installing pusher and npm as:
composer require pusher/pusher-php-server
npm install
(TO RUN NPM WE MUST INSTALL NPM)
npm run watch
(==> this will keep checking the update on resources/js/app.js and bootstrap.js)
8. Signup pusher.com and gets the following value on “Getting started”
.env file===>
PUSHER_APP_ID=943453
PUSHER_APP_KEY=0f3a2f036c90aasdfb58
PUSHER_APP_SECRET=0d068easdfasdf028300
config/broadcasting.php==>
'options' => [
'cluster' => 'ap2',
'useTLS' => true
],
9. For listening broadcast , we need echo
npm install --save laravel-echo pusher-js
10. Make listening resource(view page)
NOTE:
To listen broadcast there are various ways. They are:
- using laravel echo
- vue.js
- simple js (vanilla js)