Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon What are the steps to set up WebSocket channels in Laravel


What are the steps to set up WebSocket channels in Laravel


here are the steps to set up WebSocket channels in Laravel:

1. Install the Laravel WebSockets Package:
- Run the following command to install the `beyondcode/laravel-websockets` package:


     composer require beyondcode/laravel-websockets
     

- Publish the package's configuration and migration files:

     php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
     php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
     

- Run the migrations to create the necessary database tables:

     php artisan migrate
     

2. Configure the Broadcast Driver:
- In your `.env` file, set the `BROADCAST_DRIVER` to `pusher`:


     BROADCAST_DRIVER=pusher
     

- In your `config/broadcasting.php` file, configure the `pusher` connection to use the local WebSockets server:
php
     '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,
             'host' => '127.0.0.1',
             'port' => 6001,
             'scheme' => 'http',
         ],
     ],
     

3. Define WebSocket Channels:
- In your `routes/channels.php` file, define the WebSocket channels that your application will use:

php
     Broadcast::channel('channel-name', function ($user) {
         return true;
     });
     

- The `$user` parameter represents the authenticated user, and you can implement custom authorization logic here.

4. Implement WebSocket Functionality:
- In your Laravel application, use the `Broadcast` facade to broadcast events to the WebSocket channels:

php
     Broadcast::channel('channel-name')->send(new MessageEvent($message));
     

- On the frontend, use the `Laravel Echo` library to subscribe to the WebSocket channels and listen for events:
javascript
     window.Echo.private('channel-name')
         .listen('MessageEvent', (e) => {
             console.log(e.message);
         });
     

5. Run the WebSockets Server:
- Start the WebSockets server using the following command:


     php artisan websocket:serve
     

By following these steps, you can set up WebSocket channels in your Laravel application and enable real-time communication between the server and the client.

Citations:
[1] https://dev.to/hallorzgar/leveraging-laravel-websockets-a-practical-guide-5f4l
[2] https://www.honeybadger.io/blog/a-guide-to-using-websockets-in-laravel/
[3] https://www.youtube.com/watch?v=DIA1CJhH9dk
[4] https://gist.github.com/codewithgun/140cfe807cfaf3cfbbeffbaeebf0add5
[5] https://www.youtube.com/watch?v=5uVAJ250Wgw