### Subscribe to Private Channel with Ably Source: https://context7.com/ably-forks/laravel-echo/llms.txt Subscribes to a private channel which requires user authentication and listens for various events including custom messages, notifications, whispers, and channel subscriptions. It also provides functionality to get the Ably channel name and leave the channel. ```javascript const privateChannel = window.Echo.private('user.1'); privateChannel.listen('MessageSent', (event) => { console.log('New message:', event.message); console.log('From user:', event.from_user_id); }); privateChannel.notification((notification) => { console.log('Notification received:', notification); console.log('Type:', notification.type); console.log('Data:', notification.data); }); privateChannel.subscribed(() => { privateChannel.whisper('typing', { user: 'John', isTyping: true }, (err) => { if (err) { console.error('Whisper failed:', err); } else { console.log('Whisper sent successfully'); } }); }); privateChannel.listenForWhisper('typing', (event) => { console.log(`${event.user} is typing:`, event.isTyping); }); console.log('Ably channel name:', privateChannel.name); window.Echo.leaveChannel(privateChannel.name); ``` -------------------------------- ### Initialize Echo with Ably Driver Source: https://context7.com/ably-forks/laravel-echo/llms.txt Sets up a new Echo instance using Ably as the broadcasting driver. It configures token-based authentication and includes optional Ably client settings. The snippet also demonstrates monitoring the connection state to the Ably server. ```javascript import Echo from '@ably/laravel-echo'; import * as Ably from 'ably'; // Make Ably globally accessible window.Ably = Ably; // Initialize Echo with Ably broadcaster window.Echo = new Echo({ broadcaster: 'ably', authEndpoint: '/broadcasting/auth', // Optional Ably client options echoMessages: true, queueMessages: true, disconnectedRetryTimeout: 15000, suspendedRetryTimeout: 30000, useTls: true }); // Monitor connection state window.Echo.connector.ably.connection.on(stateChange => { if (stateChange.current === 'connected') { console.log('Connected to Ably server'); } else if (stateChange.current === 'failed') { console.error('Connection failed:', stateChange.reason); } }); ``` -------------------------------- ### Initialize Echo with Pusher Broadcaster Source: https://context7.com/ably-forks/laravel-echo/llms.txt Initializes Laravel Echo using Pusher as the broadcasting driver, suitable for applications already integrated with Pusher. It configures authentication, listens for channel events, and retrieves the Pusher socket ID. ```javascript import Echo from '@ably/laravel-echo'; import Pusher from 'pusher-js'; window.Pusher = Pusher; window.Echo = new Echo({ broadcaster: 'pusher', key: 'your-pusher-key', cluster: 'mt1', forceTLS: true, authEndpoint: '/broadcasting/auth', auth: { headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content } } }); window.Echo.connector.signin(); const channel = window.Echo.channel('updates'); channel.listen('ContentUpdated', (event) => { console.log('Content updated:', event); }); const socketId = window.Echo.socketId(); console.log('Pusher socket ID:', socketId); ``` -------------------------------- ### Subscribe to Public Channel and Listen for Events Source: https://context7.com/ably-forks/laravel-echo/llms.txt Demonstrates how to subscribe to a public channel and listen for specific broadcast events. It includes methods for handling successful subscriptions, errors, stopping listening to events, and leaving channels. The received event data is logged to the console. ```javascript // Subscribe to a public channel const channel = window.Echo.channel('orders'); // Listen for a specific event channel.listen('OrderShipped', (event) => { console.log('Order shipped:', event); // event contains: { order_id: 123, tracking_number: 'ABC123', ... } }); // Wait for successful subscription channel.subscribed(() => { console.log('Successfully subscribed to orders channel'); }); // Handle subscription errors channel.error((error) => { console.error('Subscription error:', error); }); // Stop listening to specific event channel.stopListening('OrderShipped'); // Leave the channel window.Echo.leaveChannel('public:orders'); ``` -------------------------------- ### Manage Multiple Channels and Cleanup Source: https://context7.com/ably-forks/laravel-echo/llms.txt Handles multiple channel subscriptions and properly cleans up resources when leaving channels. It shows how to subscribe to different channel types, leave individual channels by name or all channels at once, and disconnect from the broadcasting service. ```javascript // Subscribe to multiple channels const orderChannel = window.Echo.channel('orders'); const inventoryChannel = window.Echo.private('inventory'); const teamChannel = window.Echo.join('team.5'); orderChannel.listen('OrderPlaced', (event) => { console.log('New order:', event.order_id); }); inventoryChannel.listen('StockUpdated', (event) => { console.log('Stock updated:', event.product_id, event.quantity); }); teamChannel.here((members) => { console.log('Team members online:', members); }); // Leave a specific channel (all variants) window.Echo.leave('orders'); // Leaves public:orders, private:orders, presence:orders // Leave specific channel type using internal name window.Echo.leaveChannel('public:orders'); window.Echo.leaveChannel('private:inventory'); window.Echo.leaveChannel('presence:team.5'); // Leave all channels at once window.Echo.leaveAllChannels(); // Disconnect completely from the broadcasting service window.Echo.disconnect(); // On user logout, create new Echo instance after disconnect window.Echo.disconnect(); // Wait for disconnection, then create new instance setTimeout(() => { window.Echo = new Echo({ broadcaster: 'ably', // ... configuration }); }, 500); ``` -------------------------------- ### Initialize Echo with Socket.io Source: https://context7.com/ably-forks/laravel-echo/llms.txt Configures Echo to use Socket.io as the broadcasting driver for custom Socket.io server implementations. It connects to the server, sets up authentication, and subscribes to various channel types including public, private, and presence channels. ```javascript import Echo from '@ably/laravel-echo'; import io from 'socket.io-client'; window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001', auth: { headers: { 'Authorization': 'Bearer ' + document.querySelector('meta[name="api-token"]').content } } }); // Subscribe to channels const channel = window.Echo.channel('messages'); channel.listen('NewMessage', (event) => { console.log('New message:', event.message); }); // Private channel const privateChannel = window.Echo.private('user.notifications'); privateChannel.listen('NotificationSent', (event) => { console.log('Notification:', event); }); // Presence channel const presenceChannel = window.Echo.join('online'); presenceChannel.here((users) => { console.log('Online users:', users); }); ``` -------------------------------- ### Handle Channel Lifecycle Events Source: https://context7.com/ably-forks/laravel-echo/llms.txt Manages channel subscription lifecycle including successful subscriptions, errors, and cleanup. It demonstrates how to register and unregister callbacks for subscription success and errors, and how to handle specific error codes. ```javascript const channel = window.Echo.private('user-activity.123'); // Register subscription success callback channel.subscribed(() => { console.log('Successfully subscribed to channel'); // Perform actions after successful subscription channel.listen('ActivityLogged', (event) => { console.log('Activity:', event); }); // Send initial presence data if (channel.enter) { channel.enter({ timestamp: Date.now() }, (err) => { if (!err) console.log('Presence entered'); }); } }); // Register error callback channel.error((error) => { console.error('Channel error:', error); // Handle specific error states if (error.code === 40142) { console.error('Token expired, need to reauthenticate'); } }); // Unregister specific error callback const errorHandler = (err) => console.error('Error:', err) channel.error(errorHandler); // Later remove it channel.unregisterError(errorHandler); // Unregister all error callbacks channel.unregisterError(); // Similarly for subscribed callbacks const subscribedHandler = () => console.log('Subscribed!'); channel.subscribed(subscribedHandler); channel.unregisterSubscribed(subscribedHandler); ``` -------------------------------- ### Format Event Names with EventFormatter Source: https://context7.com/ably-forks/laravel-echo/llms.txt Uses the EventFormatter utility to properly format event names with namespaces for Laravel compatibility. It handles different event naming conventions and allows dynamic namespace changes or disabling namespaces. ```javascript import { EventFormatter } from '@ably/laravel-echo'; // Create event formatter with namespace const formatter = new EventFormatter('App\Events'); // Format event with namespace const formatted1 = formatter.format('UserRegistered'); console.log(formatted1); // "App\Events\UserRegistered" // Format event starting with dot (no namespace) const formatted2 = formatter.format('.CustomEvent'); console.log(formatted2); // "CustomEvent" // Format event starting with backslash (no namespace) const formatted3 = formatter.format('\GlobalEvent'); console.log(formatted3); // "GlobalEvent" // Change namespace dynamically formatter.setNamespace('App\Notifications'); const formatted4 = formatter.format('NewMessage'); console.log(formatted4); // "App\Notifications\NewMessage" // Disable namespace formatter.setNamespace(false); const formatted5 = formatter.format('PlainEvent'); console.log(formatted5); // "PlainEvent" // Usage in channel listening const channel = window.Echo.channel('updates'); // Listen with automatic namespace formatting channel.listen('ContentUpdated', (event) => { // Listens for "App\Events\ContentUpdated" console.log(event); }); // Listen without namespace by prefixing with dot channel.listen('.RawEvent', (event) => { // Listens for "RawEvent" exactly console.log(event); }); ``` -------------------------------- ### Initialize Echo with Custom Token Function (Laravel Sanctum) Source: https://context7.com/ably-forks/laravel-echo/llms.txt Configures Echo to use a custom token retrieval function, suitable for integrating with Laravel Sanctum or other custom authentication methods. It utilizes axios to make a POST request to a specified authentication endpoint for obtaining the token. ```javascript import Echo from '@ably/laravel-echo'; import * as Ably from 'ably'; import axios from 'axios'; window.Ably = Ably; window.Echo = new Echo({ broadcaster: 'ably', useTls: true, requestTokenFn: async (channelName, existingToken) => { const postData = { channel_name: channelName, token: existingToken }; const response = await axios.post('/api/broadcasting/auth', postData); return response.data; } }); // Socket ID is base64 URL encoded JSON with connectionKey and clientId const socketId = window.Echo.socketId(); console.log('Socket ID:', socketId); ``` -------------------------------- ### Listen to All Events on a Channel with Ably Source: https://context7.com/ably-forks/laravel-echo/llms.txt Subscribes to all events broadcast on a specified channel without needing to name individual event types. It allows for dynamic handling of incoming events and provides the ability to stop listening. ```javascript const channel = window.Echo.channel('notifications'); channel.listenToAll((eventName, data, metadata) => { console.log('Event received:', eventName); console.log('Data:', data); console.log('Metadata:', metadata); switch(eventName) { case 'App\Events\UserRegistered': console.log('New user registered:', data.user); break; case 'App\Events\SystemAlert': console.log('System alert:', data.message); break; default: console.log('Unknown event:', eventName); } }); channel.stopListeningToAll(); ``` -------------------------------- ### Subscribe to Presence Channel with Ably Source: https://context7.com/ably-forks/laravel-echo/llms.txt Joins a presence channel to track subscribed users, receive notifications when users join or leave, listen for regular events, and manage presence status. It also supports sending whispers to channel members and leaving the channel. ```javascript const presenceChannel = window.Echo.join('chat.1'); presenceChannel.here((members) => { console.log('Current members:', members); }); presenceChannel.joining((member) => { console.log('User joined:', member.name); }); presenceChannel.leaving((member) => { console.log('User left:', member.name); }); presenceChannel.listen('MessageSent', (event) => { console.log('Message in chat:', event.text); }); presenceChannel.subscribed(() => { presenceChannel.enter({ status: 'online', last_seen: Date.now() }, (err) => { if (err) { console.error('Failed to enter presence:', err); } }); }); presenceChannel.update({ status: 'away' }, (err) => { if (err) { console.error('Failed to update presence:', err); } }); presenceChannel.whisper('user-activity', { action: 'started_recording' }, (err) => { if (err) { console.error('Failed to send whisper:', err); } }); presenceChannel.leave({ status: 'offline' }); window.Echo.leaveChannel(presenceChannel.name); ``` -------------------------------- ### HTTP Request Interceptors with Echo and Axios Source: https://context7.com/ably-forks/laravel-echo/llms.txt Automatically attaches the socket ID to HTTP requests using interceptors for Laravel's broadcast authentication and event exclusion. Supports Axios and jQuery AJAX, and can be disabled if not needed. ```javascript import Echo from '@ably/laravel-echo'; import * as Ably from 'ably'; import axios from 'axios'; window.Ably = Ably; // Initialize Echo (interceptors are registered automatically) window.Echo = new Echo({ broadcaster: 'ably', authEndpoint: '/broadcasting/auth' }); // Axios interceptor is automatically registered // X-Socket-Id header is added to all requestsaxios.post('/api/update-profile', { name: 'John Doe' }).then(response => { console.log('Profile updated'); // If backend broadcasts ProfileUpdated event with socket ID check, // this client won't receive its own broadcast }); // Disable automatic interceptors const echoNoInterceptors = new Echo({ broadcaster: 'ably', authEndpoint: '/broadcasting/auth', withoutInterceptors: true }); // Manually add socket ID to specific requests const config = { headers: { 'X-Socket-Id': window.Echo.socketId() } }; axios.post('/api/send-message', { text: 'Hello' }, config); // jQuery AJAX is also automatically intercepted (if jQuery is available) $.ajax({ url: '/api/action', method: 'POST', data: { action: 'perform' }, success: (data) => { console.log('Action performed'); // X-Socket-Id header automatically included } }); // Turbo requests are also intercepted (if Turbo is available) // No additional configuration needed ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.