Self Hosted Websockets with Laravel
From this article, you will learn how to use self-hosted Websockets with Laravel. I am assuming you have already setup Laravel on the server.
Step 1. Install Laravel WebSockets via composer
composer require beyondcode/laravel-websockets
It will install laravel-websockets package to your Laravel. This package replates all APIs of Pusher on PHP and JavaScript side.
Step 2. Publish the migration file
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
This package comes with a migration to store statistic information while running your WebSocket server
Step 3. Run the migrations with
php artisan migrate
Step 4. Publish the WebSocket configuration
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
Step 5. Set environment variables
Open Laravel .env file and make following changes
Set Broadcast driver
BROADCAST_DRIVER=pusher
we can use pusher because Laravel Websockets use the same APIs as Pusher.
Set Socket server details
PUSHER_HOST=<server host name>
PUSHER_PORT=<socket port>
PUSHER_SCHEME=><scheme>
PUSHER_APP_ID=<you can set anything here>
PUSHER_APP_KEY=<you can set anything here>
PUSHER_APP_SECRET=<you can set anything here>
PUSHER_APP_CLUSTER=<we are not using cluseter, null>
Step 6. Run Laravel Websockets 🛰
php artisan websockets:serve
Open WebSocket dashboard
<Host Name>/laravel-websockets
If you are on localhost try
http://localhost/laravel-websockets
Let's celebrate. You just did it 😎