Introduction to Laravel WebSockets: Real-Time Applications with Laravel


Laravel WebSockets is a package for the Laravel PHP framework that enables real-time communication capabilities for web applications. With it, developers can create applications that communicate with the server in real-time, offering users live notifications, dynamic updates, chat features, and more without refreshing the page. Unlike traditional polling methods, WebSockets establish a persistent connection, allowing continuous data flow between the client and server.


In this article, we’ll explore how Laravel WebSockets work, the key features, and how to set up and use them in your Laravel application.


What is Laravel WebSockets?


Laravel WebSockets is an open-source package developed by Beyond Code that provides a self-hosted WebSocket server to handle WebSocket connections in Laravel applications. It replaces the need for services like Pusher or other external WebSocket services, enabling developers to create real-time applications without additional monthly fees or external dependencies.


Key Features of Laravel WebSockets


1. Real-time Events: It enables you to broadcast events from your server directly to clients in real-time.

2. No Third-party Dependence: Since it is self-hosted, you avoid the costs and limitations of third-party WebSocket services.

3. Dashboard Monitoring: Laravel WebSockets comes with a built-in dashboard that lets you monitor active connections, metrics, and sent messages in real time.

4. Easy Integration with Laravel Echo: Laravel Echo is a JavaScript library that provides an expressive API for subscribing to channels and listening for events. It works seamlessly with Laravel WebSockets.

5. Support for Presence and Private Channels: Laravel WebSockets supports public, private, and presence channels, which are useful for implementing features like live user lists and private chat rooms.


Setting Up Laravel WebSockets


Here’s a step-by-step guide on setting up Laravel WebSockets in your Laravel project:


Step 1: Install Laravel WebSockets Package


To get started, add the Laravel WebSockets package to your Laravel project. Run the following command:


composer require beyondcode/laravel-websockets


After installing, publish the configuration file with:


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


This will add a `websockets.php` configuration file to your `config` directory.


Step 2: Configure Your Broadcasting


In Laravel, events are broadcast over WebSockets using the broadcasting system. Set up the broadcasting in the `config/broadcasting.php` file to use the `pusher` driver. Update your `.env` file with your app information as follows:


BROADCAST_DRIVER=pusher


PUSHER_APP_ID=your-app-id

PUSHER_APP_KEY=your-app-key

PUSHER_APP_SECRET=your-app-secret

PUSHER_HOST=127.0.0.1

PUSHER_PORT=6001

PUSHER_SCHEME=http

PUSHER_APP_CLUSTER=mt1


Step 3: Run the WebSocket Server


Laravel WebSockets provides an artisan command to start the WebSocket server:


php artisan websockets:serve


This will run the WebSocket server locally, and you can access the WebSockets dashboard by navigating to `http://127.0.0.1:8000/laravel-websockets`.


Step 4: Configure Laravel Echo (Frontend)


Laravel Echo helps manage WebSocket connections and subscriptions on the frontend. To use Echo with Laravel WebSockets, install Laravel Echo and Pusher JS libraries in your application:


npm install --save laravel-echo pusher-js


Then, configure Echo to use the Pusher driver in your JavaScript file:


import 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,

    wsHost: window.location.hostname,

    wsPort: 6001,

    forceTLS: false,

    disableStats: true,

});


Step 5: Broadcasting an Event


To test broadcasting, create an event in Laravel by running:


php artisan make:event ExampleEvent


In the event class, specify the `broadcastOn` method to define the channel for broadcasting:


public function broadcastOn()

{

    return new Channel('example-channel');

}


To trigger the event, use the following in your controller or any other part of your application:


event(new ExampleEvent());


On the frontend, you can listen for the event like so:


window.Echo.channel('example-channel')

    .listen('ExampleEvent', (e) => {

        console.log(e);

    });



Real-World Applications of Laravel WebSockets


1. Real-time Notifications: Laravel WebSockets allows you to push notifications to users instantly, which is especially useful for live updates in social media apps, e-commerce order status updates, and more.

2. Live Chats: Real-time messaging in chat applications requires constant communication between the server and the client, which Laravel WebSockets easily handles.

3. Collaborative Editing: For tools like collaborative document editing, Laravel WebSockets lets multiple users make updates simultaneously and see changes in real-time.

4. Online Games: Multiplayer games can use WebSockets to synchronize game state between multiple players.


Advantages of Using Laravel WebSockets


  • Cost-Effective: Hosting your WebSocket server eliminates the need for third-party services, saving costs, especially as your application scales.
  • Ecosystem Integration: It integrates seamlessly with Laravel’s native broadcasting and queueing systems.
  • Full Control: You control your WebSocket server, allowing you to customize and optimize it for your application's specific needs.
  • Real-Time Dashboard: Laravel WebSockets provides a built-in dashboard for monitoring and debugging connections.


Laravel WebSockets adds a powerful real-time dimension to your Laravel applications, enabling seamless integration of real-time features like notifications, chats, and more. Using Laravel WebSockets and Laravel Echo, you can eliminate dependency on third-party services, gain full control, and scale efficiently. Real-time capabilities can elevate user experiences, and with Laravel WebSockets, you can add these features to your application with ease and cost-efficiency.