PHPackages                             opekunov/laravel-centrifugo-broadcaster - 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. opekunov/laravel-centrifugo-broadcaster

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

opekunov/laravel-centrifugo-broadcaster
=======================================

Centrifugo broadcaster for Laravel 8.75-11.x and Centrifugo &gt;= 5.0

v3.0.1(3mo ago)49461.3k—6.4%21[1 PRs](https://github.com/Opekunov/laravel-centrifugo-broadcaster/pulls)MITPHPPHP ^8.0|^8.1|^8.2|^8.3|^8.4CI passing

Since May 31Pushed 2mo ago3 watchersCompare

[ Source](https://github.com/Opekunov/laravel-centrifugo-broadcaster)[ Packagist](https://packagist.org/packages/opekunov/laravel-centrifugo-broadcaster)[ Docs](https://github.com/opekunov/laravel-centrifugo-broadcaster)[ RSS](/packages/opekunov-laravel-centrifugo-broadcaster/feed)WikiDiscussions 3.x Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (20)Used By (0)

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

[![Latest Version](https://camo.githubusercontent.com/cf6447f68f49c4eb89ce0f642b351446fa02b1cc2cc679d1fafe04abaa716441/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f4f70656b756e6f762f6c61726176656c2d63656e7472696675676f2d62726f61646361737465722e7376673f7374796c653d666c61742d737175617265)](https://github.com/Opekunov/laravel-centrifugo-broadcaster/releases)[![Tests](https://github.com/Opekunov/laravel-centrifugo-broadcaster/actions/workflows/tests.yml/badge.svg?branch=3.x)](https://github.com/Opekunov/laravel-centrifugo-broadcaster/actions/workflows/tests.yml)[![Code Quality](https://github.com/Opekunov/laravel-centrifugo-broadcaster/actions/workflows/code-quality.yml/badge.svg?branch=3.x)](https://github.com/Opekunov/laravel-centrifugo-broadcaster/actions/workflows/code-quality.yml)[![Coverage](https://camo.githubusercontent.com/ca5bfa7d2969feebea7f86932278af2130f908244c8de89a3a556c633b1a0ec3/68747470733a2f2f636f6465636f762e696f2f67682f4f70656b756e6f762f6c61726176656c2d63656e7472696675676f2d62726f61646361737465722f6272616e63682f332e782f67726170682f62616467652e737667)](https://codecov.io/gh/Opekunov/laravel-centrifugo-broadcaster)[![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 5-6 Broadcaster
==================================

[](#laravel-centrifugo-5-6-broadcaster)

Centrifugo 5-6 broadcast driver for Laravel 8.75 - 12.x
--------------------------------------------------------

[](#centrifugo-5-6-broadcast-driver-for-laravel-875---12x-)

> For Centrifugo 4.x use [version 2.x](https://github.com/Opekunov/laravel-centrifugo-broadcaster/tree/2.x)
> 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 5.x and 6.x](https://github.com/centrifugal/centrifugo/) 🚀
- Uses new HTTP API format introduced in Centrifugo 5.x 📡
- Wrapper over [Centrifugo HTTP API](https://centrifugal.dev/docs/server/server_api/) 🔌
- Authentication with JWT token (HMAC algorithm) 🗝️

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

[](#requirements)

- PHP &gt;= 8.0 (including 8.4)
- Laravel 8.75 - 12.x
- ext-json
- Centrifugo Server 5.x or newer (see [here](https://github.com/centrifugal/centrifugo))

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

[](#installation)

Require this package with composer:

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

**Laravel 10 and below:** Open your `config/app.php` and uncomment `BroadcastServiceProvider`:

```
return [

    // .... //

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

    // .... //

];
```

**Laravel 11+:** Run the install command which will automatically create the necessary configuration:

```
php artisan install:broadcasting
```

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 the broadcast driver setting in your `.env` file!

**Laravel 11+:**

```
BROADCAST_CONNECTION=centrifugo

```

**Laravel 10 and below:**

```
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/broadcasting)

### Channel authentication example:

[](#channel-authentication-example)

Laravel

```
// routes/channels.php

// In Centrifugo 5+, channel namespaces are separated by ':'. The '$' prefix is not used.
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)

```
npm install centrifuge
```

```
import { Centrifuge, UnauthorizedError } from 'centrifuge';

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

// Connection state events
client.on('connected', (ctx) => {
  console.log('Connected:', ctx.client, 'transport:', ctx.transport);
});

client.on('disconnected', (ctx) => {
  console.log('Disconnected:', ctx.code, ctx.reason);
});

// Getting a subscription token from your Laravel application.
// Don't forget to add 'path' => [..., 'broadcasting/auth'] to your application's cors.php file
async function getSubscriptionToken(ctx) {
  const res = await fetch('/broadcasting/auth', {
    method: 'POST',
    headers: new Headers({ 'Content-Type': 'application/json' }),
    body: JSON.stringify(ctx),
  });
  if (!res.ok) {
    if (res.status === 403) {
      throw new UnauthorizedError();
    }
    throw new Error(`Unexpected status code ${res.status}`);
  }
  const data = await res.json();
  return data.token;
}

// Subscribe to a private channel
const sub = client.newSubscription('private:chat', {
  getToken: getSubscriptionToken,
});

// Listen for messages
sub.on('publication', (ctx) => {
  console.log('New message:', ctx.data);
});

sub.on('subscribed', (ctx) => {
  console.log('Subscribed to', ctx.channel);
});

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

### Broadcasting example

[](#broadcasting-example)

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

```
