PHPackages                             ollyxar/websockets-chat - 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. ollyxar/websockets-chat

ActiveLibrary

ollyxar/websockets-chat
=======================

Laravel WebSockets Chat

2.0(8y ago)431.1k4MITPHPPHP &gt;=7.1

Since Oct 23Pushed 8y ago5 watchersCompare

[ Source](https://github.com/ollyxar/websockets-chat)[ Packagist](https://packagist.org/packages/ollyxar/websockets-chat)[ Docs](https://ollyxar.com/websockets)[ RSS](/packages/ollyxar-websockets-chat/feed)WikiDiscussions master Synced today

READMEChangelog (2)Dependencies (2)Versions (4)Used By (0)

Laravel WebSocket chat server
=============================

[](#laravel-websocket-chat-server)

[![Version](https://camo.githubusercontent.com/dfb6b64120c48c2d7ba040057aedefaa2ca3107b821ac7e9a1386816cd054484/68747470733a2f2f706f7365722e707567782e6f72672f6f6c6c797861722f776562736f636b6574732d636861742f762f737461626c652e737667)](https://camo.githubusercontent.com/dfb6b64120c48c2d7ba040057aedefaa2ca3107b821ac7e9a1386816cd054484/68747470733a2f2f706f7365722e707567782e6f72672f6f6c6c797861722f776562736f636b6574732d636861742f762f737461626c652e737667)[![Downloads](https://camo.githubusercontent.com/4a2c9566b2dd79be2a76aa27f393334a585d69bd94a82f0b5a1d727a2b4dcd15/68747470733a2f2f706f7365722e707567782e6f72672f6f6c6c797861722f776562736f636b6574732d636861742f642f746f74616c2e737667)](https://camo.githubusercontent.com/4a2c9566b2dd79be2a76aa27f393334a585d69bd94a82f0b5a1d727a2b4dcd15/68747470733a2f2f706f7365722e707567782e6f72672f6f6c6c797861722f776562736f636b6574732d636861742f642f746f74616c2e737667)[![License](https://camo.githubusercontent.com/972d2bfdd3093f09adde9195cd6bd6e07327e6a3f0213b4ebf00871925efa81b/68747470733a2f2f706f7365722e707567782e6f72672f6f6c6c797861722f776562736f636b6574732d636861742f6c6963656e73652e737667)](https://camo.githubusercontent.com/972d2bfdd3093f09adde9195cd6bd6e07327e6a3f0213b4ebf00871925efa81b/68747470733a2f2f706f7365722e707567782e6f72672f6f6c6c797861722f776562736f636b6574732d636861742f6c6963656e73652e737667)

[![logo](https://camo.githubusercontent.com/0a7d53ac739a399c11278b2e73943d4b6acac6956d45e106d48ce45bf2ecbb76/68747470733a2f2f692e696d6775722e636f6d2f4541524f4777542e6a7067)](https://camo.githubusercontent.com/0a7d53ac739a399c11278b2e73943d4b6acac6956d45e106d48ce45bf2ecbb76/68747470733a2f2f692e696d6775722e636f6d2f4541524f4777542e6a7067)

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

[](#requirements)

- Unix (extension [pcntl\_fork](http://php.net/manual/function.pcntl-fork.php))
- PHP 7.1+
- Laravel 5
- composer

Installing WebSockets Chat
--------------------------

[](#installing-websockets-chat)

The recommended way to install WebSockets is through [Composer](http://getcomposer.org).

```
# Install Composer
curl -sS https://getcomposer.org/installer | php
```

Next, run the Composer command to install the latest stable version of WebSockets:

```
php composer.phar require ollyxar/websockets-chat
```

After updating composer, add the service provider to the `providers` array in `config/app.php`

```
Ollyxar\WSChat\WSChatServiceProvider::class,
```

Configuration
-------------

[](#configuration)

You can customize variables bellow by adding config-file: `websockets-chat.php` in the config folder:

parameterdescriptionexamplehandlerHandler Class (extends of Worker)`\App\MyHandler`hostHost (ip)`0.0.0.0`portPort`2083`worker\_countCount of forked process`4`use\_sslUsed protocol`false`certPEM certificate`/etc/nginx/conf.d/wss.pem`pass\_phrasePEM certificate pass phrase`secret$#%`Extended Handler class
----------------------

[](#extended-handler-class)

This is example how to use Handler with User authentication. If you have default configuration and file-session-storage you can use this example.

First you have to install auth-helper:

```
php composer.phar require ollyxar/laravel-auth
```

Then create your `Handler.php`:

```
namespace App;

use Generator;
use Ollyxar\LaravelAuth\FileAuth;
// or you can use RedisAuth if you're storing sessions in the Redis-server:
// use Ollyxar\LaravelAuth\RedisAuth;
use Ollyxar\WebSockets\{
   Frame,
   Handler as Worker,
   Dispatcher
};

/**
 * Class Handler
 * @package App
 */
class Handler extends Worker
{
    /**
     * Connected users
     *
     * @var array
     */
    protected $users = [];

    /**
     * Append connected user
     *
     * @param array $headers
     * @param $socket
     * @return bool
     */
    private function fillUser(array $headers, $socket): bool
    {
        if ($userId = FileAuth::getUserIdByHeaders($headers)) {
            // allow only one connection for worker per user
            if (!in_array($userId, $this->users)) {
                $this->users[(int)$socket] = $userId;
                return true;
            }
        }

        return false;
    }

    /**
     * @param $client
     * @return Generator
     */
    protected function onConnect($client): Generator
    {
        $userName = User::where('id', (int)$this->users[(int)$client])->first()->name;
        yield Dispatcher::async($this->broadcast(Frame::encode(json_encode([
            'type'    => 'system',
            'message' => $userName . ' connected.'
        ]))));
    }

    /**
     * @param array $headers
     * @param $socket
     * @return bool
     */
    protected function validateClient(array $headers, $socket): bool
    {
        return $this->fillUser($headers, $socket);
    }

    /**
     * @param $clientNumber
     * @return Generator
     */
    protected function onClose($clientNumber): Generator
    {
        $user = User::where('id', (int)@$this->users[$clientNumber])->first();
        $userName = data_get($user, 'name', '[GUEST]');

        yield Dispatcher::async($this->broadcast(Frame::encode(json_encode([
            'type'    => 'system',
            'message' => $userName . " disconnected."
        ]))));

        unset($this->users[$clientNumber]);
        yield;
    }

    /**
     * @param string $message
     * @param int $socketId
     * @return Generator
     */
    protected function onClientMessage(string $message, int $socketId): Generator
    {
        $message = json_decode($message);
        $userName = User::where('id', (int)$this->users[$socketId])->first()->name;
        $userMessage = $message->message;

        $response = Frame::encode(json_encode([
            'type'    => 'usermsg',
            'name'    => $userName,
            'message' => $userMessage
        ]));

        yield Dispatcher::async($this->broadcast($response));
    }
}
```

Then add markup to the front:

```

        Send

```

And JS code:

```
var wsUri = "ws://laravel5.dev:2083",
    ws = new WebSocket(wsUri);

ws.onopen = function () {
    var el = document.createElement('div');
    el.classList.add('system-msg');
    el.innerText = 'Connection established';
    document.getElementById('message-box').appendChild(el);
};

document.getElementById('message').addEventListener('keydown', function (e) {
    if (e.keyCode === 13) {
        document.getElementById('send-btn').click();
    }
});

document.getElementById('send-btn').addEventListener('click', function () {
    var mymessage = document.getElementById('message').value;

    if (mymessage === '') {
        alert("Enter Some message Please!");
        return;
    }

    var objDiv = document.getElementById("message-box");
    objDiv.scrollTop = objDiv.scrollHeight;

    var msg = {
        message: mymessage
    };
    ws.send(JSON.stringify(msg));
});

ws.onmessage = function (ev) {
    var msg = JSON.parse(ev.data),
        type = msg.type,
        umsg = msg.message,
        uname = msg.name;

    var el = document.createElement('div');

    if (type === 'usermsg') {
        el.innerHTML = '' + uname + ' : ' + umsg + '';
        document.getElementById('message-box').appendChild(el);
    }
    if (type === 'system') {
        el.classList.add('system-msg');
        el.innerText = umsg;
        document.getElementById('message-box').appendChild(el);
    }

    document.getElementById('message').value = '';

    var objDiv = document.getElementById('message-box');
    objDiv.scrollTop = objDiv.scrollHeight;
};

ws.onerror = function (e) {
    var el = document.createElement('div');
    el.classList.add('system-error');
    el.innerText = 'Error Occurred - ' + e.data;
    document.getElementById('message-box').appendChild(el);
};
ws.onclose = function () {
    var el = document.createElement('div');
    el.classList.add('system-msg');
    el.innerText = 'Connection Closed';
    document.getElementById('message-box').appendChild(el);
};
```

### Starting WebSocket Server

[](#starting-websocket-server)

```
php artisan websockets-chat:run
```

### Sending direct message to the server

[](#sending-direct-message-to-the-server)

```
php artisan websockets-chat:send "Hello from system!"
```

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~137 days

Total

2

Last Release

2983d ago

Major Versions

1.0 → 2.02018-03-09

### Community

Maintainers

![](https://www.gravatar.com/avatar/94a445da70d70ada49f927d76cb247d3df7a6b4cafc5bd78abcd559d73d76e7c?d=identicon)[alexslipknot](/maintainers/alexslipknot)

---

Top Contributors

[![alexslipknot](https://avatars.githubusercontent.com/u/8543759?v=4)](https://github.com/alexslipknot "alexslipknot (1 commits)")

---

Tags

artisan-commandchatlaravel5websocket-chatwebsocket-serverwebsocketslaravellibraryWebSocketschat

### Embed Badge

![Health badge](/badges/ollyxar-websockets-chat/health.svg)

```
[![Health](https://phpackages.com/badges/ollyxar-websockets-chat/health.svg)](https://phpackages.com/packages/ollyxar-websockets-chat)
```

###  Alternatives

[laravel/reverb

Laravel Reverb provides a real-time WebSocket communication backend for Laravel applications.

1.5k9.4M48](/packages/laravel-reverb)[rajentrivedi/tokenizer-x

TokenizerX calculates required tokens for given prompt

91214.0k3](/packages/rajentrivedi-tokenizer-x)[nikolag/laravel-square

Square API integration with Laravel built on nikolag/core

3827.3k](/packages/nikolag-laravel-square)[zachflower/eloquent-interactions

An implementation of the interactor pattern for Laravel.

1312.3k](/packages/zachflower-eloquent-interactions)[alexeykhr/laravel-clickhouse-migrations

Clickhouse migrations for Laravel

102.9k](/packages/alexeykhr-laravel-clickhouse-migrations)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
