Note: this is not related with setup of this project. you can setup this project similar to any other laravel project.
- Install the Pusher PHP Server Library:
composer require pusher/pusher-php-server
- uncomment the
BroadcastServiceProvider
inconfig/app.php
:
App\Providers\BroadcastServiceProvider::class,
- Set the
BROADCAST_DRIVER
in the.env
file:
BROADCAST_DRIVER=pusher
- Set the Pusher credentials in the
.env
file:
PUSHER_APP_ID=your-app-id
PUSHER_APP_KEY=your-app-key
PUSHER_APP_SECRET=your-app-secret
PUSHER_APP_CLUSTER=your-app-cluster
- Install the Laravel Echo and Pusher JS libraries:
npm install --save laravel-echo pusher-js
- uncomment js code in
resources/js/bootstrap.js
:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
...
});
- run
npm run dev
to compile the assets.
- Create an event:
php artisan make:event TestBroadcast
- Modify the event class:
implement the
ShouldBroadcast
interface and add thebroadcastOn
method:
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class TestBroadcast implements ShouldBroadcast
{
// ...
public function broadcastOn()
{
return new Channel('test-channel');
}
}
- add channel to the
routes/channels.php
file:
Broadcast::channel('test-channel', function ($user) {
return true;
});
- Broadcast the event:
event(new TestBroadcast());
- Listen for the event:
window.Echo.channel('test-channel')
.listen('TestBroadcast', (e) => {
console.log(e);
// do something
});
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/routes/web.php#L26
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/routes/console.php#L17
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/routes/channels.php#L20
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/app/Events/TestBroadcast.php
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/resources/views/test.blade.php
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/routes/web.php#L28
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/routes/channels.php#L24
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/app/Events/ChatSent.php
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/app/Livewire/Pages/Chat.php
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/resources/views/livewire/pages/chat.blade.php
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/routes/web.php#L32
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/routes/channels.php#L16
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/app/Livewire/Pages/ExportCsv.php
- https://github.com/MrPunyapal/broadcast-with-laravel/blob/main/resources/views/livewire/pages/export-csv.blade.php
Thanks for reading. If you have any question, feel free to ask on @MrPunyapal