Real-time communication is a powerful feature in modern web applications. In Laravel 11, you can achieve this using WebSockets with Pusher and Laravel Echo. In this guide, we will walk you through setting up WebSockets in Laravel 11 using Vite as the frontend tool.
Prerequisites
Before setting up WebSockets, ensure that you have the following:
- Laravel 11 installed
- Vite configured for frontend asset bundling
- A Pusher account
- Broadcasting enabled in Laravel
Step 1: Install Laravel Broadcasting & Configure
First, install the required broadcasting package:
composer require pusher/pusher-php-server
Then, enable broadcasting in your Laravel app by updating the .env
file with the following:
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=6001
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=
Make sure to replace these values with the credentials you get from Pusher after setting up your account.
Next, publish the broadcasting configuration file if you haven’t already:
php artisan vendor:publish --tag=broadcasting-config
Then, update config/broadcasting.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'),
'useTLS' => true,
],
],
Enable broadcasting by updating bootstrap/
providers.php:
//Register your provider
App\Providers\BroadcastServiceProvider::class,
Step 2: Install Laravel Echo and Pusher for Frontend
Now, install Laravel Echo and Pusher client in your project:
npm install --save laravel-echo pusher-js
Then, update your resources/js/bootstrap.js
file:
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_PUSHER_APP_KEY,
cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
wsHost: window.location.hostname,
wsPort: 6001,
wssPort: 6001,
forceTLS: false,
disableStats: true,
});
Then, add the following to your .env
file to make Vite recognize the Pusher keys:
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
Now, restart Vite:
npm run dev
Step 3: Creating a Sample WebSocket Event
To send data to WebSockets, create a sample event:
php artisan make:event MessageSent
Edit the app/Events/MessageSent.php
file:
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastOn()
{
return ['chat-channel'];
}
public function broadcastAs()
{
return 'message.sent';
}
}
Now, dispatch this event from a controller:
use App\Events\MessageSent;
use Illuminate\Http\Request;
public function sendMessage(Request $request)
{
broadcast(new MessageSent($request->message));
return response()->json(['message' => 'Message sent successfully!']);
}
Step 4: Listening for WebSocket Messages in Frontend
Now, listen to the WebSocket messages on the frontend:
window.Echo.channel('chat-channel')
.listen('.message.sent', (data) => {
console.log('New message:', data.message);
});
Troubleshooting
If you face issues with Vite or Laravel Mix, ensure:
- Your
.env
file values are correct. - Your
package.json
has the correct settings ("type": "module"
if needed). - Pusher is properly configured.
- You restart Laravel and Vite after changes.
If you still face issues, feel free to comment or reach out via email.
Conclusion
By following this guide, you have successfully set up WebSockets in Laravel 11 using Pusher and Echo. This allows your application to send real-time updates efficiently. Now, you can expand this further by integrating it with chat applications, notifications, or other real-time features.
If you found this guide helpful, share it with others and stay tuned for more updates!