Setting up Laravel Echo with Laravel WebSockets for real-time communication involves several steps. Laravel Echo is a JavaScript library that makes it easy to work with WebSockets and other real-time communication technologies. Laravel WebSockets is a package for Laravel that provides the server-side functionality for handling WebSocket connections. Here's a step-by-step guide to help you set up and use Laravel Echo with Laravel WebSockets:
Make sure you have a Laravel project set up. If not, you can create one using the following command:
bashcomposer create-project --prefer-dist laravel/laravel your-project-name
Then, install Laravel Echo and Laravel WebSockets:
bashcomposer require pusher/pusher-php-server
composer require beyondcode/laravel-websockets
After installing Laravel WebSockets, you need to publish its configuration file and migrate the database:
bashphp artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
php artisan migrate
Next, update your .env
file with the WebSocket configuration:
envPUSHER_APP_ID=null PUSHER_APP_KEY=null PUSHER_APP_SECRET=null PUSHER_APP_CLUSTER=null
Add the following lines to your .env
file to configure Laravel WebSockets:
envBROADCAST_DRIVER=pusher PUSHER_APP_ID=your-pusher-app-id PUSHER_APP_KEY=your-pusher-app-key PUSHER_APP_SECRET=your-pusher-app-secret
Include Laravel Echo and Pusher in your project by adding the following lines to your resources/js/bootstrap.js
file:
javascriptimport Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true,
});
Update your config/broadcasting.php
file to use the Pusher driver for broadcasting:
php'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true,
],
],
],
Create a broadcasting event that will be sent to the WebSocket server. For example, you can create an event using the following command:
bashphp artisan make:event YourEventName
Update the generated event class with the data you want to broadcast.
In your controllers or wherever you want to trigger the event, use the event
function to broadcast the event:
phpevent(new YourEventName($data));
In your JavaScript components, you can listen for events using Laravel Echo. For example, you can use the following code in a Vue component:
javascriptmounted() {
Echo.channel('channel-name')
.listen('YourEventName', (event) => {
console.log(event);
});
}
Run the Laravel WebSockets server using the following command:
bashphp artisan websockets:serve
Make sure to check the documentation for the latest updates and additional features.