Using laravel-websocket in Laravel to Build Real-Time Apps

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Real-time interaction is an essential feature of modern web applications. With Laravel and the laravel-websocket package, PHP developers can easily build robust real-time applications. This tutorial will guide you through the installation, configuration, and usage of laravel-websocket to create real-time features in your Laravel applications.

Setting Up

First, install the laravel-websocket package via Composer:

composer require beyondcode/laravel-websockets

Publish the configuration file:

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

Configuring the WebSocket Server

Modify the config/websockets.php file to set up your WebSocket server:

'apps' => [
    [
        'id' => env('PUSHER_APP_ID'),
        'name' => env('APP_NAME'),
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'enable_client_messages' => true,
        'enable_statistics' => true,
    ],
],

Running the WebSocket Server

Start the WebSocket server using the Artisan command:

php artisan websockets:serve

This will start the server, and you can connect to it using your frontend implementation, like Laravel Echo or JavaScript.

Integrating with the Frontend

For this example, we’ll be using Laravel Echo with Pusher JS:

import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');

window.echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key',
    wsHost: window.location.hostname,
    wsPort: 6001,
    forceTLS: false,
    disableStats: true,
});

Now you can listen for events on a channel:

window.echo.channel('your-channel')
    .listen('.YourEvent', (e) => {
        console.log(e);
    });

Creating Events

Create a custom event in Laravel which implements ‘ShouldBroadcast’. Here’s an example:

use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class YourEvent implements ShouldBroadcast
{
    public function broadcastOn()
    {
        return new Channel('your-channel');
    }
}

Trigger this event from your application logic, and it should appear on your front end in real-time.

Presence Channels

Laravel WebSocket also supports Presence Channels which allow you to track the online presence of users:

window.echo.join('presence-channel')
    .here((users) => {
        // Users that are already present.
    })
    .joining((user) => {
        // User that joins the presence channel.
    })
    .leaving((user) => {
        // User that leaves the presence channel.
    });

Handling Authentication

Laravel-websocket allows you to authenticate private and presence channels to ensure only authorized users access them:

Broadcast::channel('private-channel', function ($user) {
    return (int) $user->id === (int) Auth::id();
});
Broadcast::channel('presence-channel', function ($user) {
    return $user;
});

Advanced Usage: Custom Controllers

You can extend the functionality of your WebSocket server by adding custom WebSocket controllers.

use BeyondCode\LaravelWebSockets\WebSockets\WebSocketHandler;
class CustomWebSocketController extends WebSocketHandler
{
    public function onOpen($connection)
    { }
    public function onClose($connection)
    { }
}

Edit the websockets.php configuration file to use your custom controller:

'handlers' => [
    'default' => MyCustomWebSocketHandler::class,
],

Securing Your WebSocket Connection

To ensure secure connections you can use SSL. Setup your SSL certificates in your broadcasting config:

'apps' => [
    [
        'id' => env('PUSHER_APP_ID'),
        // ...
        'ssl' => [
            'local_cert' => env('WEBSOCKETS_SSL_LOCAL_CERT', null),
            'local_pk' => env('WEBSOCKETS_SSL_LOCAL_PK', null),
            'passphrase' => env('WEBSOCKETS_SSL_PASSPHRASE', null),
        ],
        // ...
    ],
],

Debugging and Monitoring

Laravel-websocket provides a dashboard to monitor WebSocket connections and messages. You can access it by visiting /laravel-websockets on your app URL after you have adjusted the dashboard configuration settings in your .env file.

Conclusion

By following this guide, you have learned how to integrate real-time functionality into your Laravel applications using the laravel-websocket package. Real-time apps provide an enhanced user experience that can significantly benefit your project. Happy coding!