PHPackages                             retmix/centrifugo-broadcaster-fix - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. retmix/centrifugo-broadcaster-fix

ActiveLibrary[HTTP &amp; Networking](/categories/http)

retmix/centrifugo-broadcaster-fix
=================================

Centrifugo broadcaster for laravel 8-9.x and Centrifugo &gt;= 2.8.1

2.x-dev(3y ago)0666MITPHPPHP ^8.0|^8.1

Since Mar 13Pushed 3y agoCompare

[ Source](https://github.com/RetmixX/opekunov-centrufugo-fix-userId)[ Packagist](https://packagist.org/packages/retmix/centrifugo-broadcaster-fix)[ RSS](/packages/retmix-centrifugo-broadcaster-fix/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelogDependencies (4)Versions (1)Used By (0)

Documentation **EN** | [RU](https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/2.x/README_RU.md)

[![Latest Version](https://camo.githubusercontent.com/cf6447f68f49c4eb89ce0f642b351446fa02b1cc2cc679d1fafe04abaa716441/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f4f70656b756e6f762f6c61726176656c2d63656e7472696675676f2d62726f61646361737465722e7376673f7374796c653d666c61742d737175617265)](https://github.com/Opekunov/laravel-centrifugo-broadcaster/releases)[![StyleCI](https://camo.githubusercontent.com/8e148367846b075c1b43c324a532da286691816321016857d5e5e970313afe16/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3337323432353239312f736869656c643f6272616e63683d6d6173746572)](https://github.styleci.io/repos/372425291?branch=master)[![StyleCI](https://camo.githubusercontent.com/f3280bc3d2c709df8b70595029d654af8ab70bcb226153be44beccd575258068/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f4f70656b756e6f762f6c61726176656c2d63656e7472696675676f2d62726f61646361737465722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/Opekunov/laravel-centrifugo-broadcaster/?branch=master)[![Total Downloads](https://camo.githubusercontent.com/fc02675e5d4b7693882e42182102163947741391bcab70210dda136fa4a26941/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f70656b756e6f762f6c61726176656c2d63656e7472696675676f2d62726f61646361737465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/opekunov/laravel-centrifugo-broadcaster)[![Software License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/master/LICENSE)

Laravel Centrifugo 4 Broadcaster
================================

[](#laravel-centrifugo-4-broadcaster)

Centrifugo 4 broadcast driver for Laravel 8.75 - 9.x
-----------------------------------------------------

[](#centrifugo-4-broadcast-driver-for-laravel-875---9x-)

> For Centrifugo 2.8 - 3.x use [version 1.2.6](https://github.com/Opekunov/laravel-centrifugo-broadcaster/tree/master)

Features
--------

[](#features)

- Compatible with latest [Centrifugo 4.x](https://github.com/centrifugal/centrifugo/) 🚀
- Wrapper over [Centrifugo HTTP API](https://centrifugal.dev/docs/server/server_api/) 🔌
- Authentication with JWT token (HMAC algorithm) 🗝️

Requirements
------------

[](#requirements)

- PHP &gt;= 8.0
- Laravel 8.75 - 9.x
- guzzlehttp/guzzle 6 - 7
- Centrifugo Server 4.x or newer (see [here](https://github.com/centrifugal/centrifugo))

Installation
------------

[](#installation)

Require this package with composer:

```
composer req opekunov/laravel-centrifugo-broadcaster
```

Open your `config/app.php` and uncomment this line:

```
return [

    // .... //

    'providers' => [
        // Uncomment BroadcastServiceProvider
        App\Providers\BroadcastServiceProvider::class,
    ],

    // .... //

];
```

Open your `config/broadcasting.php` and add new `connection` like this:

```
return [

        // .... //

        'centrifugo' => [
            'driver' => 'centrifugo',
            'secret'  => env('CENTRIFUGO_SECRET'),
            'apikey'  => env('CENTRIFUGO_APIKEY'),
            'api_path' => env('CENTRIFUGO_API_PATH', '/api'), // Centrifugo api endpoint (default '/api')
            'url'     => env('CENTRIFUGO_URL', 'http://localhost:8000'), // centrifugo api url
            'verify'  => env('CENTRIFUGO_VERIFY', false), // Verify host ssl if centrifugo uses this
            'ssl_key' => env('CENTRIFUGO_SSL_KEY', null), // Self-Signed SSl Key for Host (require verify=true),
            'show_node_info' => env('CENTRIFUGO_SHOW_NODE_INFO', false), // Show node info in response with auth token
            'timeout' => env('CENTRIFUGO_TIMEOUT', 3), // Float describing the total timeout of the request to centrifugo api in seconds. Use 0 to wait indefinitely (the default is 3)
            'tries' => env('CENTRIFUGO_TRIES', 1), //Number of times to repeat the request, in case of failure (the default is 1)
            'token_expire_time' => env('CENTRIFUGO_TOKEN_EXPIRE', 120), //Default token expire time. Used in channel subscriptions /broadcasting/auth
        ],

       // .... //

];
```

Also you should add these two lines to your `.env` file:

```
CENTRIFUGO_SECRET=token_hmac_secret_key-from-centrifugo-config
CENTRIFUGO_APIKEY=api_key-from-centrifugo-config
CENTRIFUGO_URL=http://localhost:8000

```

These lines are optional:

```
CENTRIFUGO_SSL_KEY=/etc/ssl/some.pem
CENTRIFUGO_VERIFY=false
CENTRIFUGO_API_PATH=/api
CENTRIFUGO_SHOW_NODE_INFO=false
CENTRIFUGO_TIMEOUT=10
CENTRIFUGO_TRIES=1
CENTRIFUGO_TOKEN_EXPIRE=120

```

Don't forget to change `BROADCAST_DRIVER` setting in .env file!

```
BROADCAST_DRIVER=centrifugo

```

Basic Usage
-----------

[](#basic-usage)

To configure Centrifugo server, read [official documentation](https://centrifugal.dev/docs/getting-started/installation)

For broadcasting events, see [official documentation of laravel](https://laravel.com/docs/9.x/broadcasting)

### Channel authentication example:

[](#channel-authentication-example)

Laravel

```
// routes/channels.php

// IMPORTANT. In Centrifugo 4, the '$' character in front of the private channel is considered obsolete. Do not use it. https://centrifugal.dev/docs/server/channels#private-channel-prefix-
Broadcast::channel('namespace:channel', function (){
    // Some auth logic for example:
    return \Auth::user()->group === 'private-channel-group';
});

Broadcast::channel('namespace:channel-{id}', function ($user, $id){
    return $user->id === $id;
});
```

Frontend. See documentation [centrifugal/centrifuge-js](https://github.com/centrifugal/centrifuge-js)

```
// Example:
import { Centrifuge } from 'centrifuge';

// Set the base path of Laravel broadcasting.
// Don't forget to add 'path' => [..., 'broadcasting/auth'] to your application's cors.php file
const subscribeTokenEndpoint = 'http://127.0.0.1/broadcasting/auth'

const centrifuge = new Centrifuge('ws://localhost:8001/connection/websocket', {
  //CONNECTION_TOKEN must be obtained from Centrifuge::generateConnectionToken(...)
  token: 'CONNECTION_TOKEN'
})

// Set the subscription
const sub = centrifuge.newSubscription('test:test', {
  getToken: function (ctx) {
    return customGetToken(subscribeTokenEndpoint, ctx);
  },
})

// Getting a subscription token from your Laravel application.
// Important: In this example, getting a subscription token is implemented through basic fetch() without passing parameters to identify the user in your Laravel application. Use methods appropriate for your application
function customGetToken(endpoint, ctx) {
  return new Promise((resolve, reject) => {
    fetch(endpoint, {
      method: 'POST',
      headers: new Headers({ 'Content-Type': 'application/json' }),
      body: JSON.stringify(ctx)
    })
      .then(res => {
        if (!res.ok) {
          throw new Error(`Unexpected status code ${res.status}`);
        }
        return res.json();
      })
      .then(data => {
        resolve(data.token);
      })
      .catch(err => {
        reject(err);
      });
  });
}

sub.subscribe();
centrifuge.connect();
```

### Broadcasting example

[](#broadcasting-example)

Create event (for example SendMessage) with artisan `php artisan make:event SendMessageEvent`

```
