Sling Academy
Home/PHP/Using laravel-websocket in Laravel to Build Real-Time Apps

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

Last updated: January 16, 2024

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!

Next Article: How to store and read data from cache in Laravel

Previous Article: Working with Laravel Artisan Console: A Practical Guide

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array