Convert Figma logo to code with AI

beyondcode logolaravel-websockets

Websockets for Laravel. Done right.

5,067
611
5,067
0

Top Related Projects

4,828

Next-gen, Pusher-compatible, open-source WebSockets server. Simple, fast, and resilient. 📣

Socket.io server for Laravel Echo

3,744

Supercharge your Laravel application's performance.

PHP library for interacting with the Pusher Channels HTTP API

11,091

An asynchronous event driven PHP socket framework. Supports HTTP, Websocket, SSL and other custom protocols.

6,244

Asynchronous WebSocket server

Quick Overview

Laravel WebSockets is a package that allows you to implement WebSocket servers in Laravel applications without relying on external services like Pusher. It provides a drop-in Pusher replacement, enabling real-time functionality in your Laravel projects using native WebSockets.

Pros

  • Easy integration with existing Laravel applications
  • Cost-effective alternative to third-party WebSocket services
  • Supports both WebSocket and HTTP fallback connections
  • Includes a debug dashboard for monitoring WebSocket connections

Cons

  • May require additional server configuration for production use
  • Limited to Laravel ecosystem
  • Potential scalability challenges for very large applications
  • Requires PHP 7.2 or higher

Code Examples

  1. Broadcasting an event:
event(new App\Events\NewMessage($message));
  1. Configuring the WebSocket connection in JavaScript:
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    wsHost: window.location.hostname,
    wsPort: 6001,
    forceTLS: false,
    disableStats: true,
});
  1. Listening for WebSocket events:
Echo.channel('orders')
    .listen('OrderShipped', (e) => {
        console.log('Order shipped:', e.order);
    });

Getting Started

  1. Install the package:
composer require beyondcode/laravel-websockets
  1. Publish the configuration file:
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
  1. Update your .env file:
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your_app_id
PUSHER_APP_KEY=your_app_key
PUSHER_APP_SECRET=your_app_secret
PUSHER_APP_CLUSTER=mt1

LARAVEL_WEBSOCKETS_PORT=6001
  1. Start the WebSocket server:
php artisan websockets:serve
  1. Configure your Laravel application to use the WebSocket server by updating config/broadcasting.php:
'pusher' => [
    'driver' => 'pusher',
    'key' => env('PUSHER_APP_KEY'),
    'secret' => env('PUSHER_APP_SECRET'),
    'app_id' => env('PUSHER_APP_ID'),
    'options' => [
        'cluster' => env('PUSHER_APP_CLUSTER'),
        'host' => '127.0.0.1',
        'port' => 6001,
        'scheme' => 'http'
    ],
],

Competitor Comparisons

4,828

Next-gen, Pusher-compatible, open-source WebSockets server. Simple, fast, and resilient. 📣

Pros of soketi

  • Written in Node.js, potentially offering better performance for WebSocket connections
  • Supports horizontal scaling out of the box
  • Provides a REST API for managing channels and users

Cons of soketi

  • Requires a separate service to run alongside Laravel
  • May have a steeper learning curve for developers more familiar with PHP

Code Comparison

laravel-websockets:

use BeyondCode\LaravelWebSockets\WebSocketsServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->register(WebSocketsServiceProvider::class);
    }
}

soketi:

const { Soketi } = require('@soketi/soketi');

const server = new Soketi({
    appId: 'your-app-id',
    key: 'your-app-key',
    secret: 'your-app-secret'
});

server.listen(6001);

Both projects aim to provide WebSocket functionality for Laravel applications, but they take different approaches. laravel-websockets is a PHP-based solution that integrates directly into Laravel, making it easier to set up and use for developers already familiar with the framework. soketi, on the other hand, is a separate Node.js service that offers potentially better performance and scalability at the cost of added complexity in deployment and management.

The choice between the two depends on specific project requirements, team expertise, and infrastructure considerations. laravel-websockets may be more suitable for smaller projects or teams with primarily PHP expertise, while soketi could be a better fit for larger-scale applications requiring high performance and scalability.

Socket.io server for Laravel Echo

Pros of Laravel Echo Server

  • Built with Node.js, potentially offering better performance for WebSocket connections
  • Supports multiple drivers (Redis, SQLite) for storing presence channel members
  • Can be run as a standalone server, separate from the main Laravel application

Cons of Laravel Echo Server

  • Requires a separate Node.js process, increasing infrastructure complexity
  • Less tightly integrated with Laravel ecosystem compared to Laravel WebSockets
  • May require additional configuration and maintenance

Code Comparison

Laravel Echo Server configuration:

module.exports = {
  authHost: 'http://localhost',
  authEndpoint: '/broadcasting/auth',
  clients: [],
  database: 'redis',
  databaseConfig: {
    redis: {},
    sqlite: {
      databasePath: '/database/laravel-echo-server.sqlite'
    }
  }
}

Laravel WebSockets configuration:

'websockets' => [
    'path' => 'laravel-websockets',
    'middleware' => [
        'web',
        \BeyondCode\LaravelWebSockets\Dashboard\Http\Middleware\Authorize::class,
    ],
    'statistics' => [
        'model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class,
    ],
],

Both packages offer robust WebSocket solutions for Laravel applications, with Laravel WebSockets providing tighter Laravel integration and Laravel Echo Server offering potentially better performance and flexibility.

3,744

Supercharge your Laravel application's performance.

Pros of Octane

  • Significantly improves application performance by keeping the application in memory
  • Supports multiple high-performance application servers (Swoole, RoadRunner)
  • Provides seamless integration with Laravel's existing features and ecosystem

Cons of Octane

  • Requires additional server setup and configuration
  • May not be compatible with all existing Laravel packages and extensions
  • Potential memory leaks if not managed properly in long-running processes

Code Comparison

Laravel-WebSockets:

use BeyondCode\LaravelWebSockets\WebSocketsServer;

$server = new WebSocketsServer();
$server->start();

Octane:

use Laravel\Octane\Octane;

$octane = new Octane($app);
$octane->start();

Key Differences

  • Laravel-WebSockets focuses specifically on WebSocket functionality, while Octane is a broader performance optimization solution
  • Octane requires changes to the application structure and deployment process, whereas Laravel-WebSockets can be more easily integrated into existing projects
  • Laravel-WebSockets is primarily for real-time communication, while Octane enhances overall application performance

Use Cases

  • Choose Laravel-WebSockets for projects requiring real-time communication without major architectural changes
  • Opt for Octane when seeking significant performance improvements across the entire Laravel application, especially for high-traffic websites or APIs

PHP library for interacting with the Pusher Channels HTTP API

Pros of pusher-http-php

  • Established and widely-used solution with extensive documentation
  • Seamless integration with Pusher's hosted service
  • Supports multiple programming languages beyond PHP

Cons of pusher-http-php

  • Requires a paid subscription for production use
  • Limited control over the underlying WebSocket infrastructure
  • Dependency on external services may introduce latency

Code Comparison

laravel-websockets:

use BeyondCode\LaravelWebSockets\Facades\WebSocketsRouter;

WebSocketsRouter::webSocket('/my-websocket', MyWebSocketHandler::class);

pusher-http-php:

$pusher = new Pusher\Pusher($app_key, $app_secret, $app_id);
$pusher->trigger('my-channel', 'my-event', ['message' => 'Hello World']);

Summary

laravel-websockets is a self-hosted WebSocket server for Laravel applications, offering more control and potentially lower costs for high-traffic applications. It's designed specifically for Laravel and provides seamless integration with the framework's existing broadcasting features.

pusher-http-php, on the other hand, is a client library for interacting with Pusher's hosted WebSocket service. It offers a more straightforward setup process and managed infrastructure but comes with associated costs and less control over the underlying WebSocket server.

The choice between these two depends on factors such as budget, scalability requirements, and the level of control needed over the WebSocket infrastructure.

11,091

An asynchronous event driven PHP socket framework. Supports HTTP, Websocket, SSL and other custom protocols.

Pros of Workerman

  • More lightweight and flexible, not tied to Laravel framework
  • Supports multiple protocols beyond WebSockets (e.g., HTTP, TCP, UDP)
  • Generally offers better performance and scalability for high-concurrency scenarios

Cons of Workerman

  • Requires more manual configuration and setup compared to Laravel WebSockets
  • Less integrated with Laravel ecosystem and features
  • Steeper learning curve for developers already familiar with Laravel

Code Comparison

Workerman:

use Workerman\Worker;

$worker = new Worker('websocket://0.0.0.0:8080');
$worker->onMessage = function($connection, $data) {
    $connection->send('Hello ' . $data);
};
Worker::runAll();

Laravel WebSockets:

use BeyondCode\LaravelWebSockets\WebSocketsServer;

$server = new WebSocketsServer();
$server->listen(8080);

The Workerman example shows a more low-level approach, giving developers direct control over the WebSocket server's behavior. Laravel WebSockets, on the other hand, provides a higher-level abstraction that integrates seamlessly with Laravel's existing broadcasting system.

While Workerman offers more flexibility and potentially better performance, Laravel WebSockets excels in its ease of use within the Laravel ecosystem and its out-of-the-box integration with Laravel's authentication and authorization mechanisms.

6,244

Asynchronous WebSocket server

Pros of Ratchet

  • Framework-agnostic, can be used with any PHP project
  • More flexible and customizable for complex WebSocket implementations
  • Supports both WebSocket and socket.io protocols

Cons of Ratchet

  • Requires more setup and configuration compared to Laravel WebSockets
  • Less integrated with Laravel ecosystem and features
  • May require additional libraries for certain functionalities

Code Comparison

Ratchet:

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new MyWebSocketHandler()
        )
    ),
    8080
);
$server->run();

Laravel WebSockets:

php artisan websockets:serve

Summary

Ratchet is a more versatile WebSocket solution for PHP projects, offering greater flexibility and customization options. However, it requires more setup and may be less convenient for Laravel-specific applications. Laravel WebSockets, on the other hand, provides a more integrated and streamlined experience for Laravel developers, with easier setup and built-in Laravel features. The choice between the two depends on the project requirements, existing tech stack, and desired level of customization.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Laravel WebSockets 🛰

[!NOTE]
Laravel WebSockets is no longer maintained. If you are looking for a PHP-based WebSocket solution, check out Laravel Reverb which is also built on top of ReactPHP and allows you to horizontally scale the WebSocket server.

Latest Version on Packagist GitHub Workflow Status Quality Score Total Downloads

Bring the power of WebSockets to your Laravel application. Drop-in Pusher replacement, SSL support, Laravel Echo support and a debug dashboard are just some of its features.

https://tinkerwell.app/?ref=github

Documentation

For installation instructions, in-depth usage and deployment details, please take a look at the official documentation.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email marcel@beyondco.de instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.