Laravel Echo is a JavaScript library that makes it easy to work with WebSockets and broadcasting events in a Laravel application. Laravel Echo Server is a Node.js server that can be used to broadcast events to the Laravel Echo library. Here's a step-by-step guide on how to implement Laravel Echo with Laravel Echo Server:
bash# Install Laravel Echo
npm install --save laravel-echo pusher-js
# Install Laravel Echo Server globally
npm install -g laravel-echo-server
In your Laravel application, open the .env
file and set the broadcasting driver to pusher
:
envBROADCAST_DRIVER=pusher
Next, configure the Pusher credentials in the same file:
envPUSHER_APP_ID=your-app-id PUSHER_APP_KEY=your-app-key PUSHER_APP_SECRET=your-app-secret PUSHER_APP_CLUSTER=your-app-cluster
In your Laravel application, create a new file resources/js/bootstrap.js
(if it doesn't exist) and add the following:
javascriptimport Echo from 'laravel-echo';
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true,
});
Include the Laravel Echo and Bootstrap.js file in your layout or view:
html<script src="{{ asset('js/bootstrap.js') }}" defer></script>
In your terminal, run the following command to start Laravel Echo Server:
bashlaravel-echo-server start
Make sure to configure Laravel Echo Server by following the prompts. You'll need to set your Pusher credentials, app key, secret, cluster, etc.
In your Laravel application, you can broadcast events using Laravel's event system. For example, you might broadcast an event when a new message is created:
php// In your controller or wherever you want to broadcast the event
broadcast(new NewMessage($message));
In your JavaScript, you can listen for events and react accordingly:
javascriptEcho.channel('chat-room')
.listen('NewMessage', (event) => {
console.log('New Message:', event.message);
});
Replace chat-room
with the channel you want to listen to and NewMessage
with the name of the event you're broadcasting.
Make sure to check the documentation for any updates or changes specific to the versions you are using.
=== Happy Coding :)