### Manual Docker Setup and Management (Bash) Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/tests/README.md Provides commands for manually setting up, running, and cleaning up Docker containers for Centrifugo v5 and v6. Useful for more granular control over the testing environment. ```bash # Start both Centrifugo v5 (port 8001) and v6 (port 8002) composer test:docker:setup # Start only v5 composer test:docker:setup:v5 # Start only v6 composer test:docker:setup:v6 # Run integration tests against v5 composer test:integration:v5 # Run integration tests against v6 composer test:integration:v6 # Stop all containers composer test:docker:cleanup ``` -------------------------------- ### Install Laravel Centrifugo Broadcaster using Composer Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md This command installs the package using Composer. Ensure you have Composer installed and configured for your Laravel project. ```bash composer req opekunov/laravel-centrifugo-broadcaster ``` -------------------------------- ### Install Laravel Centrifugo Broadcaster via Composer Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Installs the Laravel Centrifugo Broadcaster package using Composer. This is the first step in integrating Centrifugo with your Laravel application. ```bash composer require opekunov/laravel-centrifugo-broadcaster ``` -------------------------------- ### Run Quick Unit and Security Tests (Bash) Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/tests/README.md Execute unit, security, and HTTP client tests without requiring Docker. These commands are run using Composer and are suitable for quick checks. ```bash # Run all unit tests (no server required) composer test:unit # Run security tests composer test:security # Run HTTP client tests composer test:http ``` -------------------------------- ### Docker Troubleshooting Commands (Bash) Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/tests/README.md Useful bash commands for troubleshooting Docker-related issues, such as checking container status, viewing logs, and performing forceful cleanups. ```bash # Check if containers are running cd tests/Docker && docker compose ps # View Centrifugo logs cd tests/Docker && docker compose logs centrifugo-v5 cd tests/Docker && docker compose logs centrifugo-v6 # Force cleanup cd tests/Docker && docker compose down --volumes --remove-orphans ``` -------------------------------- ### Get Server Info Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Retrieve statistics and information about the running Centrifugo server nodes. ```APIDOC ## GET /info ### Description Get stats information about running server nodes. ### Method GET ### Endpoint /info ### Response #### Success Response (200) - **nodes** (array) - Information about each server node. - **status** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "nodes": [ {"node_id": "node1", "num_clients": 100}, {"node_id": "node2", "num_clients": 150} ], "status": true } ``` ``` -------------------------------- ### Wait for Server Readiness Script (PHP) Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/tests/README.md A PHP script to wait for Centrifugo servers to become ready. It takes one or more server URLs as arguments and polls them until they respond. ```php php tests/Docker/wait-for-server.php http://localhost:8001 http://localhost:8002 ``` -------------------------------- ### Laravel Centrifugo Controller Examples Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Demonstrates various Centrifugo operations within a Laravel controller using the Centrifugo facade. This includes publishing messages to channels, generating connection and subscription tokens, and retrieving channel presence information. Requires the Centrifugo service to be available. ```php publish('news', ['message' => 'Hello world']); // Generate connection token $token = $centrifugo->generateConnectionToken((string)Auth::id(), 0, [ 'name' => Auth::user()->name, ]); // Generate subscription token $expire = now()->addDay(); //or you can use Unix: $expire = time() + 60 * 60 * 24; $token = $centrifugo->generateSubscriptionToken((string)Auth::id(), 'channel', $expire, [ 'name' => Auth::user()->name, ]); //Get a list of currently active channels. $centrifugo->channels(); //Get channel presence information (all clients currently subscribed on this channel). $centrifugo->presence('news'); } } ``` -------------------------------- ### Test Coverage Generation (Bash) Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/tests/README.md Command to generate HTML test coverage reports using PHPUnit. The generated report can be viewed in a web browser. ```bash ./vendor/bin/phpunit --coverage-html coverage/ # Then open coverage/index.html in your browser. ``` -------------------------------- ### CI/CD Test Suite Execution (Bash) Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/tests/README.md Commands for executing the full test suite in a Continuous Integration/Continuous Deployment environment. This includes setting up servers, running tests against both versions, and cleaning up. ```bash # Full test suite on both v5 and v6 composer test:docker # Or step by step composer test:docker:setup # Start both servers + wait composer test:integration:v5 # Run against v5 composer test:integration:v6 # Run against v6 composer test:docker:cleanup # Stop containers ``` -------------------------------- ### Run Integration Tests with Docker (Bash) Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/tests/README.md Commands to run integration tests using Docker, including full cycles, specific Centrifugo versions, and targeting custom server URLs. These tests require Docker and Docker Compose. ```bash # Full cycle: start both v5 & v6, run tests on both, cleanup composer test:docker # Test only against Centrifugo v5 composer test:docker:v5 # Test only against Centrifugo v6 composer test:docker:v6 # Run integration tests against a running server (default: localhost:8001) composer test:integration # Run against a specific server URL CENTRIFUGO_URL=http://localhost:8002 composer test:integration ``` -------------------------------- ### Get Channel Presence Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Get information about all clients currently subscribed to a channel. ```APIDOC ## GET /presence ### Description Get channel presence information (all clients currently subscribed on this channel). ### Method GET ### Endpoint /presence ### Parameters #### Query Parameters - **channel** (string) - Required - The channel to get presence information for. ### Response #### Success Response (200) - **clients** (array) - An array of client information. - **status** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "clients": [ {"user_id": "user1", "client_data": {}}, {"user_id": "user2", "client_data": {}} ], "status": true } ``` ``` -------------------------------- ### GET /api/presence/{channel} Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Retrieves detailed information about all clients currently subscribed to a channel, including their connection data. ```APIDOC ## GET /api/presence/{channel} ### Description Retrieves detailed information about all clients currently subscribed to a channel, including their connection data. ### Method GET ### Endpoint `/api/presence/{channel}` ### Parameters #### Path Parameters - **channel** (string) - Required - The channel for which to retrieve presence information. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **channel** (string) - The name of the channel. - **online_users** (array) - An array of objects, each representing an online user. - **user_id** (string) - The unique identifier of the user. - **client_id** (string) - The unique identifier of the client connection. - **name** (string) - The name of the user (if available). - **count** (integer) - The total number of online users in the channel. #### Response Example ```json { "channel": "chat:room_1", "online_users": [ { "user_id": "user_123", "client_id": "client_id_1", "name": "John" }, { "user_id": "user_456", "client_id": "client_id_2", "name": "Jane" } ], "count": 2 } ``` ``` -------------------------------- ### GET /api/presence/stats Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Returns a lightweight summary of presence information including the number of connected clients and unique users for specified channels. ```APIDOC ## GET /api/presence/stats ### Description Returns a lightweight summary of presence information including the number of connected clients and unique users for specified channels. ### Method GET ### Endpoint `/api/presence/stats` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **channel_stats** (object) - An object where keys are channel names and values are statistics for that channel. - **clients** (integer) - The total number of connections to the channel. - **users** (integer) - The number of unique users connected to the channel. - **total_users** (integer) - The sum of unique users across all queried channels. #### Response Example ```json { "channel_stats": { "chat:general": { "clients": 15, "users": 10 }, "chat:support": { "clients": 5, "users": 5 }, "chat:sales": { "clients": 20, "users": 18 } }, "total_users": 33 } ``` ``` -------------------------------- ### Get Channel Presence Stats Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Get a short form of channel presence information, including the number of clients. ```APIDOC ## GET /presenceStats ### Description Get channel presence information in short form (number of clients). ### Method GET ### Endpoint /presenceStats ### Parameters #### Query Parameters - **channel** (string) - Required - The channel to get presence statistics for. ### Response #### Success Response (200) - **num_clients** (integer) - The number of clients currently subscribed to the channel. - **status** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "num_clients": 10, "status": true } ``` ``` -------------------------------- ### List Channels Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Get a list of currently active channels on the Centrifugo server. ```APIDOC ## GET /channels ### Description Get channels information (list of currently active channels). ### Method GET ### Endpoint /channels ### Parameters #### Query Parameters - **pattern** (string) - Optional - A pattern to filter channel names. ### Response #### Success Response (200) - **channels** (array) - An array of active channel names. - **status** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "channels": ["chat-room", "notifications"], "status": true } ``` ``` -------------------------------- ### Laravel Event Broadcasting Integration - PHP Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Demonstrates how to create broadcast events in Laravel that integrate with the Centrifugo driver. This allows real-time updates to be sent to connected clients when events occur in your application. The example shows a `NewMessageEvent` that broadcasts to a specific channel. ```php $this->message, 'user_id' => $this->userId, 'timestamp' => now()->toIso8601String() ]; } public function broadcastOn(): Channel { return new Channel('chat:room_' . $this->roomId); // For private channels: return new PrivateChannel('chat:room_' . $this->roomId); } } // Usage in controller class MessageController { public function send(Request $request) { $message = $request->input('message'); $roomId = $request->input('room_id'); // Dispatch the event - automatically broadcasts via Centrifugo event(new NewMessageEvent($message, auth()->id(), $roomId)); return response()->json(['sent' => true]); } } ``` -------------------------------- ### info - Get Server Node Information Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Retrieves statistics and information about running Centrifugo server nodes. This is useful for monitoring and debugging purposes. ```APIDOC ## GET /info ### Description Retrieves statistics and information about running Centrifugo server nodes, useful for monitoring and debugging. ### Method GET ### Endpoint `/info` ### Parameters This endpoint does not accept any parameters. ### Request Example ```php $info = $centrifugo->info(); ``` ### Response #### Success Response (200) - **nodes** (array) - An array of objects, where each object represents a Centrifugo node and its statistics (uid, name, version, num_clients, num_users, num_channels, uptime). #### Response Example ```json { "result": { "nodes": [ { "uid": "node_1", "name": "centrifugo-1", "version": "5.0.0", "num_clients": 150, "num_users": 100, "num_channels": 25, "uptime": 86400 } ] } } ``` ``` -------------------------------- ### JavaScript Frontend Connection and Subscription with Centrifugo Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Connects a JavaScript frontend to Centrifugo using the centrifuge-js library. It demonstrates obtaining a connection token, subscribing to private channels with dynamic token generation, and handling subscription and publication events. Requires npm package installation and a backend endpoint for token generation. ```bash npm install centrifuge ``` ```javascript 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(); ``` -------------------------------- ### Laravel Event Broadcasting for Centrifugo Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Defines a Laravel event that can be broadcast using Centrifugo. It includes methods to specify the broadcast name, the data to be sent, and the channel(s) on which the event should be broadcast. This example uses `ShouldBroadcastNow` for immediate broadcasting. ```php messageText = $messageText; } /** * The event's broadcast name. * * @return string */ public function broadcastAs() { //example event broadcast name. Show in Web Socket JSON return 'message.new'; } /** * Get the data to broadcast. * * @return array */ public function broadcastWith() { return ['message' => $this->messageText]; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new Channel('public:chat'); // or return new PrivateChannel('private:chat'); } } ``` -------------------------------- ### Get Channel Presence Statistics - PHP Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Returns a lightweight summary of presence information for multiple channels, including the number of connected clients and unique users. It iterates through a list of channels and aggregates the statistics. Requires the Centrifugo class. ```php presenceStats($channel); // Response structure: // [ // 'result' => [ // 'num_clients' => 15, // Total connections (one user can have multiple) // 'num_users' => 10 // Unique users // ] // ] $stats[$channel] = [ 'clients' => $result['result']['num_clients'] ?? 0, 'users' => $result['result']['num_users'] ?? 0 ]; } return response()->json([ 'channel_stats' => $stats, 'total_users' => array_sum(array_column($stats, 'users')) ]); } } ``` -------------------------------- ### Get Channel Presence Information - PHP Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Retrieves detailed information about all clients subscribed to a channel. It processes the raw presence data to extract user ID, client ID, and user name. Requires the Centrifugo class and a channel name as input. ```php presence('chat:room_1'); // Response structure: // [ // 'result' => [ // 'presence' => [ // 'client_id_1' => [ // 'client' => 'client_id_1', // 'user' => 'user_123', // 'conn_info' => ['name' => 'John', 'role' => 'admin'], // 'chan_info' => ['joined_at' => '2024-01-15T10:00:00Z'] // ], // 'client_id_2' => [ // 'client' => 'client_id_2', // 'user' => 'user_456', // 'conn_info' => ['name' => 'Jane', 'role' => 'member'] // ] // ] // ] // ] $onlineUsers = []; if (isset($presence['result']['presence'])) { foreach ($presence['result']['presence'] as $clientId => $info) { $onlineUsers[] = [ 'user_id' => $info['user'], 'client_id' => $info['client'], 'name' => $info['conn_info']['name'] ?? 'Unknown' ]; } } return response()->json([ 'channel' => $channel, 'online_users' => $onlineUsers, 'count' => count($onlineUsers) ]); } } ``` -------------------------------- ### Get Server Node Information - PHP Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Fetches statistics and information about running Centrifugo server nodes. This is useful for monitoring the health and performance of your Centrifugo deployment. The function returns details like node UID, name, version, number of clients, users, channels, and uptime. ```php info(); // Response structure: // [ // 'result' => [ // 'nodes' => [ // [ // 'uid' => 'node_1', // 'name' => 'centrifugo-1', // 'version' => '5.0.0', // 'num_clients' => 150, // 'num_users' => 100, // 'num_channels' => 25, // 'uptime' => 86400 // ] // ] // ] // ] $nodes = $info['result']['nodes'] ?? []; $totalClients = array_sum(array_column($nodes, 'num_clients')); $totalUsers = array_sum(array_column($nodes, 'num_users')); return response()->json([ 'nodes' => $nodes, 'total_clients' => $totalClients, 'total_users' => $totalUsers, 'node_count' => count($nodes) ]); } } ``` -------------------------------- ### Get Channel History Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Retrieve the history of messages sent into a channel. ```APIDOC ## GET /history ### Description Get channel history information (list of last messages sent into channel). ### Method GET ### Endpoint /history ### Parameters #### Query Parameters - **channel** (string) - Required - The channel to get history from. - **limit** (integer) - Optional - The maximum number of messages to retrieve. Defaults to 0 (all). - **offset** (integer) - Optional - The offset for retrieving messages. - **epoch** (string) - Optional - The epoch timestamp to start retrieving messages from. - **reverse** (boolean) - Optional - Whether to retrieve messages in reverse order. Defaults to false. ### Response #### Success Response (200) - **messages** (array) - An array of historical messages. - **status** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "messages": [ {"id": 1, "data": {"message": "Old message"}}, {"id": 2, "data": {"message": "Another old message"}} ], "status": true } ``` ``` -------------------------------- ### Configure Laravel App Service Provider Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Uncomment the BroadcastServiceProvider in your `config/app.php` file to enable broadcasting. This is a standard Laravel configuration step. ```php return [ // .... 'providers' => [ // Uncomment BroadcastServiceProvider App\Providers\BroadcastServiceProvider::class, ], // .... ]; ``` -------------------------------- ### GET /api/history/{channel} Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Retrieves the history of messages published to a channel. The channel must have history enabled in Centrifugo server configuration. ```APIDOC ## GET /api/history/{channel} ### Description Retrieves the history of messages published to a channel. The channel must have history enabled in Centrifugo server configuration. ### Method GET ### Endpoint `/api/history/{channel}` ### Parameters #### Path Parameters - **channel** (string) - Required - The channel for which to retrieve message history. #### Query Parameters - **limit** (integer) - Optional - The maximum number of messages to retrieve. Defaults to 50. - **reverse** (boolean) - Optional - If true, retrieves messages in reverse order (newest first). Defaults to false. - **offset** (integer) - Optional - Retrieve messages after a specific offset. - **epoch** (string) - Optional - Retrieve messages after a specific epoch. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **channel** (string) - The name of the channel. - **messages** (array) - An array of message publication objects. - **data** (object) - The data payload of the message. - **offset** (integer) - The offset of the message. - **pagination** (object) - Pagination information. - **offset** (integer) - The offset for the next page of results. - **epoch** (string) - The epoch for the next page of results. #### Response Example ```json { "channel": "chat:room_1", "messages": [ { "data": { "message": "Hello" }, "offset": 1 }, { "data": { "message": "World" }, "offset": 2 } ], "pagination": { "offset": 100, "epoch": "ABCD" } } ``` ``` -------------------------------- ### Manage Server-Side Subscriptions with Centrifugo Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Illustrates how to programmatically subscribe or unsubscribe users from channels directly from the server-side without client interaction. This is useful for managing user access and notifications. ```php // Subscribe a user to a channel from the server side $centrifugo->subscribe('notifications:user1', 'user1'); // With additional info and data $centrifugo->subscribe('notifications:user1', 'user1', info: ['role' => 'admin'], data: ['message' => 'Welcome!'] ); // Unsubscribe a user from a channel $centrifugo->unsubscribe('notifications:user1', 'user1'); // Disconnect a user entirely $centrifugo->disconnect('user1'); ``` -------------------------------- ### Set Optional Centrifugo Configuration in .env Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Configure optional settings for the Centrifugo connection in your `.env` file. These include SSL key, verification, API path, node info display, timeouts, retries, and token expiration. ```dotenv 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 ``` -------------------------------- ### Centrifugo Health Check (Bash) Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/tests/README.md A simple curl command to check if the Centrifugo server is responding and healthy. This is useful for diagnosing connection issues. ```bash curl http://localhost:8001/health ``` -------------------------------- ### Track User Presence with Centrifugo Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Shows how to retrieve presence information for a channel, including full client details or just connection statistics. Requires presence to be enabled in Centrifugo server configuration. ```php // Get full presence info (all clients with their data) $presence = $centrifugo->presence('chat:room1'); // Get short presence stats (number of clients and unique users) $stats = $centrifugo->presenceStats('chat:room1'); ``` ```javascript const sub = client.newSubscription('chat:room1', { joinLeave: true, // Enable join/leave events }); // Track who is online sub.on('subscribed', async (ctx) => { const presence = await sub.presence(); for (const [clientId, info] of Object.entries(presence.clients)) { console.log(`Online: ${info.user} (${clientId})`); } }); // Real-time join/leave events sub.on('join', (ctx) => { console.log('User joined:', ctx.info.user); }); sub.on('leave', (ctx) => { console.log('User left:', ctx.info.user); }); sub.subscribe(); ``` -------------------------------- ### Set Centrifugo Credentials in .env File Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Add your Centrifugo secret, API key, and URL to your project's `.env` file. These credentials are required for the Laravel broadcaster to authenticate with your Centrifugo instance. ```dotenv CENTRIFUGO_SECRET=token_hmac_secret_key-from-centrifugo-config CENTRIFUGO_APIKEY=api_key-from-centrifugo-config CENTRIFUGO_URL=http://localhost:8000 ``` -------------------------------- ### Get Active Channels List - PHP Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Retrieves a list of all active channels on the Centrifugo server. It supports filtering channels by a specified pattern, such as 'chat:*' or 'notifications:*'. The function returns channel information including the number of connected clients for each channel. ```php channels(); // Response structure: // [ // 'result' => [ // 'channels' => [ // 'chat:room_1' => ['num_clients' => 5], // 'chat:room_2' => ['num_clients' => 3], // 'notifications:user_123' => ['num_clients' => 1] // ] // ] // ] // Filter channels by pattern (e.g., all chat channels) $chatChannels = $centrifugo->channels('chat:*'); // Filter notification channels $notificationChannels = $centrifugo->channels('notifications:*'); return response()->json([ 'all_channels' => $allChannels['result']['channels'] ?? [], 'chat_channels' => $chatChannels['result']['channels'] ?? [], 'notification_channels' => $notificationChannels['result']['channels'] ?? [] ]); } } ``` -------------------------------- ### Subscribe User to Channel Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Subscribe a user to a channel on the server side. ```APIDOC ## POST /subscribe ### Description Subscribe user to channel (server-side). ### Method POST ### Endpoint /subscribe ### Parameters #### Query Parameters - **channel** (string) - Required - The channel to subscribe the user to. - **user** (string) - Required - The ID of the user to subscribe. - **info** (array) - Optional - Additional information about the subscription. - **data** (array) - Optional - Data associated with the subscription. ### Request Example ```json { "channel": "private-channel", "user": "user123", "info": {"role": "admin"} } ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "status": true } ``` ``` -------------------------------- ### Generate Connection Token Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Generate a token for a user to establish a connection with the Centrifugo server. ```APIDOC ## POST /generateConnectionToken ### Description Generate connection token. ### Method POST ### Endpoint /generateConnectionToken ### Parameters #### Query Parameters - **userId** (string|integer) - Required - The ID of the user for whom the token is generated. - **exp** (integer) - Optional - The expiration time for the token (Unix timestamp). Defaults to 0 (no expiration). - **info** (array) - Optional - Additional information to include in the token. - **channels** (array) - Optional - Channels the user is initially subscribed to. ### Request Example ```json { "userId": "user123", "exp": 1678886400, "info": {"plan": "premium"}, "channels": ["public-channel"] } ``` ### Response #### Success Response (200) - **token** (string) - The generated connection token. - **status** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "status": true } ``` ``` -------------------------------- ### Server-Side Channel Subscription with Centrifugo (PHP) Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Subscribes a user to a channel from the server side without client interaction. This method can be used for system-initiated subscriptions and supports passing custom information and initial data to the subscription. It requires the Centrifugo client instance. ```php subscribe($channel, $userId); // Subscription with custom info and initial data $result = $centrifugo->subscribe( channel: 'chat:support', user: $userId, info: [ 'role' => 'customer', 'priority' => 'high', 'ticket_id' => 'TKT-789' ], data: [ 'welcome_message' => 'A support agent will be with you shortly.', 'queue_position' => 3 ] ); // Response on success: ['result' => []] return response()->json([ 'subscribed' => true, 'user' => $userId, 'channel' => $channel ]); } } ``` -------------------------------- ### Laravel Event Broadcasting Integration Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Integrates with Laravel's native broadcasting system using the Centrifugo driver to create and dispatch broadcast events. ```APIDOC ## Laravel Event Broadcasting Integration ### Description Create broadcast events that integrate with Laravel's native broadcasting system using the Centrifugo driver. ### Usage 1. **Define a Broadcast Event:** Create a new event class that implements `ShouldBroadcastNow`. ```php // app/Events/NewMessageEvent.php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class NewMessageEvent implements ShouldBroadcastNow { use Dispatchable, InteractsWithSockets, SerializesModels; public function __construct( public string $message, public int $userId, public string $roomId ) {} public function broadcastAs(): string { return 'message.new'; } public function broadcastWith(): array { return [ 'message' => $this->message, 'user_id' => $this->userId, 'timestamp' => now()->toIso8601String() ]; } public function broadcastOn(): Channel { return new Channel('chat:room_' . $this->roomId); // For private channels: return new PrivateChannel('chat:room_' . $this->roomId); } } ``` 2. **Dispatch the Event:** Dispatch the event from your controller or service. ```php // Usage in controller use Illuminate\Http\Request; use App\Events\NewMessageEvent; class MessageController { public function send(Request $request) { $message = $request->input('message'); $roomId = $request->input('room_id'); // Dispatch the event - automatically broadcasts via Centrifugo event(new NewMessageEvent($message, auth()->id(), $roomId)); return response()->json(['sent' => true]); } } ``` ### Response When an event is dispatched using `ShouldBroadcastNow`, Laravel automatically handles broadcasting it through the configured Centrifugo driver. The response from the `send` method in the example controller is a simple JSON indicating success. ``` -------------------------------- ### Set Centrifugo Environment Variables for Laravel Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Sets the necessary environment variables in the `.env` file for the Laravel Centrifugo Broadcaster. These variables include the broadcast driver and Centrifugo server credentials. ```env # .env BROADCAST_DRIVER=centrifugo CENTRIFUGO_SECRET=token_hmac_secret_key-from-centrifugo-config CENTRIFUGO_APIKEY=api_key-from-centrifugo-config CENTRIFUGO_URL=http://localhost:8000 ``` -------------------------------- ### Configure Laravel Broadcasting for Centrifugo Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Configures the broadcasting connection in Laravel's `config/broadcasting.php` file to use the Centrifugo driver. It requires Centrifugo server credentials and connection details. ```php // config/broadcasting.php return [ 'default' => env('BROADCAST_DRIVER', 'centrifugo'), 'connections' => [ 'centrifugo' => [ 'driver' => 'centrifugo', 'secret' => env('CENTRIFUGO_SECRET'), 'apikey' => env('CENTRIFUGO_APIKEY'), 'api_path' => env('CENTRIFUGO_API_PATH', '/api'), 'url' => env('CENTRIFUGO_URL', 'http://localhost:8000'), 'verify' => env('CENTRIFUGO_VERIFY', false), 'ssl_key' => env('CENTRIFUGO_SSL_KEY', null), 'show_node_info' => env('CENTRIFUGO_SHOW_NODE_INFO', false), 'timeout' => env('CENTRIFUGO_TIMEOUT', 3), 'tries' => env('CENTRIFUGO_TRIES', 1), 'token_expire_time' => env('CENTRIFUGO_TOKEN_EXPIRE', 120), ], ], ]; ``` -------------------------------- ### Get Channel Message History - PHP Source: https://context7.com/opekunov/laravel-centrifugo-broadcaster/llms.txt Retrieves the history of messages published to a channel, provided history is enabled in Centrifugo server configuration. Supports fetching a limited number of messages, in reverse order, and paginating through older messages using offset and epoch. Requires the Centrifugo class and a channel name. ```php history($channel, limit: 50); // Response structure: // [ // 'result' => [ // 'publications' => [ // ['data' => ['message' => 'Hello'], 'offset' => 1], // ['data' => ['message' => 'World'], 'offset' => 2] // ], // 'offset' => 100, // 'epoch' => 'ABCD' // ] // ] // Get messages in reverse order (newest first) $latestMessages = $centrifugo->history($channel, limit: 10, reverse: true); // Pagination: get messages after a specific position $offset = $history['result']['offset'] ?? 0; $epoch = $history['result']['epoch'] ?? ''; $olderMessages = $centrifugo->history( channel: $channel, limit: 50, offset: $offset, epoch: $epoch ); return response()->json([ 'channel' => $channel, 'messages' => $history['result']['publications'] ?? [], 'pagination' => [ 'offset' => $offset, 'epoch' => $epoch ] ]); } } ``` -------------------------------- ### Generate Subscription Token Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Generate a token for a user to subscribe to a specific channel. ```APIDOC ## POST /generateSubscriptionToken ### Description Generate subscription token. ### Method POST ### Endpoint /generateSubscriptionToken ### Parameters #### Query Parameters - **userId** (string|integer) - Required - The ID of the user. - **channel** (string) - Required - The channel to subscribe to. - **exp** (integer) - Optional - The expiration time for the token (Unix timestamp). Defaults to 0 (no expiration). - **info** (array) - Optional - Additional information to include in the token. - **override** (array) - Optional - Override options for the subscription. ### Request Example ```json { "userId": "user123", "channel": "private-channel", "exp": 1678886400, "info": {"role": "editor"} } ``` ### Response #### Success Response (200) - **token** (string) - The generated subscription token. - **status** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "status": true } ``` ``` -------------------------------- ### Manage Message History with Centrifugo Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Demonstrates how to retrieve, paginate, and remove message history from a channel using Centrifugo. Requires history to be configured on the Centrifugo server. ```php // Get the last 10 messages from the channel $history = $centrifugo->history('chat:room1', limit: 10); // Get messages in reverse order (newest first) $history = $centrifugo->history('chat:room1', limit: 10, reverse: true); // Pagination: get messages from a specific position $history = $centrifugo->history('chat:room1', limit: 50, offset: 100, epoch: 'EPOCH'); // Remove channel history $centrifugo->historyRemove('chat:room1'); ``` ```javascript const sub = client.newSubscription('chat:room1'); sub.on('subscribed', async (ctx) => { // Get the last 50 messages const history = await sub.history({ limit: 50 }); history.publications.forEach((pub) => { console.log('Message:', pub.data, 'offset:', pub.offset); }); // Get messages since a specific position (for pagination) const newMessages = await sub.history({ since: { offset: history.offset, epoch: history.epoch }, limit: 100, }); // Get messages in reverse order (newest first) const latest = await sub.history({ limit: 10, reverse: true }); }); sub.subscribe(); ``` -------------------------------- ### Configure Centrifugo Broadcast Connection in Laravel Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Add a new 'centrifugo' connection to your `config/broadcasting.php` file. This defines the settings for connecting to your Centrifugo server, including API credentials and endpoints. ```php 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 ], // .... ]; ``` -------------------------------- ### Set Broadcast Driver in .env File Source: https://github.com/opekunov/laravel-centrifugo-broadcaster/blob/3.x/README.md Change the `BROADCAST_DRIVER` setting in your `.env` file to 'centrifugo' to use the Centrifugo broadcaster. This tells Laravel to use this specific driver for broadcasting events. ```dotenv BROADCAST_DRIVER=centrifugo ```