WebSocket allows two-way communication: the server can send messages to the browser and the browser - the client - can respond back via the same connection.
I am implementing Chat Application in Laravel 6 using:
- Laravel Echo JavaScript Package (not laravel-echo-server),
- Laravel WebSockets
- pusher-js.
I already get it worked that the server triggers events and the client listens to those events as following.
- Install Laravel WebSockets package.
composer require beyondcode/laravel-websockets
- Configure
config/broadcasting.php
.
'pusher' => [
'driver' => 'pusher',
'key' => xxx,
'secret' => xxx,
'app_id' => xxx,
'options' => [
'cluster' => xxx,
'encrypted' => true,
'useTLS' => true,
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'https',
],
],
]
- Configure
config/websockets.php
'apps' => [
[
'id' => xxx,
'name' => xxx,
'key' => xxx,
'secret' => xxx,
'enable_client_messages' => true,
'enable_statistics' => true,
],
],
- Install
Pusher
server.
composer require pusher/pusher-php-server "~3.0"
- Set broadcasting driver to use
pusher
in.env
file.
BROADCAST_DRIVER=pusher
- Use
laravel-echo
andpusher-js
on my client side.
import Echo from "laravel-echo"
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-pusher-key',
wsHost: window.location.hostname,
wsPort: 6001,
disableStats: true,
});
- Start WebSockets server.
php artisan websockets:serve
- On the server-side, trigger events with an event class that implements
ShouldBroadcastNow
class.
event(new MyEventClass((object)$message));
Everything works fine. In step 8, I trigger events from the server-side.
Note that I am not using the official Pusher server, I just utilize the Pusher API implementations and pusher-js
but point the Laravel Echo JavaScript package
to the local Laravel WebSockets server
, configured in step 6.
Please do not confus Laravel Echo JavaScript package
with laravel-echo-server
of Socket.IO Server
. I am not using Socket.IO Server
.
Now instead of triggering events on the server-side as shown in step 8, I want to tigger events from the client-side since WebSocket allows two-way communication. How can I do that in Laravel
with Laravel Echo JavaScript Package
, Laravel WebSockets PHP package
?