Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ekko Broadcast Laravel Package

edwin-luijten/ekko-broadcast

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require edwin-luijten/ekko-broadcast
    

    Publish the config file:

    php artisan vendor:publish --provider="EdwinLuijten\EkkoBroadcast\EkkoBroadcastServiceProvider"
    
  2. Configuration Open config/ekko-broadcast.php and set your preferred broadcast driver (e.g., pusher, redis, log). Example for 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'),
        'encrypted' => true,
    ],
    
  3. First Use Case: Broadcasting an Event Create an event (e.g., ChatMessageSent):

    php artisan make:event ChatMessageSent
    

    Update the event to use EkkoBroadcastEvent:

    use EdwinLuijten\EkkoBroadcast\EkkoBroadcastEvent;
    
    class ChatMessageSent extends EkkoBroadcastEvent
    {
        public $message;
    
        public function __construct($message)
        {
            $this->message = $message;
        }
    
        public function broadcastOn()
        {
            return new Channel('chat');
        }
    }
    

    Fire the event in your controller:

    event(new ChatMessageSent('Hello, world!'));
    
  4. Frontend Setup Include the Ekko.js client in your Blade template:

    <script src="https://cdn.jsdelivr.net/npm/ekko-broadcast@1.0.0/dist/ekko.min.js"></script>
    

    Initialize the client:

    const ekko = new Ekko({
        key: 'YOUR_PUSHER_KEY',
        cluster: 'YOUR_CLUSTER',
        encrypted: true
    });
    
    ekko.subscribe('chat', (message) => {
        console.log('New message:', message);
    });
    

Implementation Patterns

Core Workflows

1. Event-Driven Broadcasting

  • Pattern: Use Laravel events to decouple broadcasting logic from your business logic.
  • Example:
    // In your controller or service
    event(new OrderShipped($orderId));
    
    // In your event
    class OrderShipped extends EkkoBroadcastEvent
    {
        public $orderId;
    
        public function __construct($orderId)
        {
            $this->orderId = $orderId;
        }
    
        public function broadcastOn()
        {
            return new Channel('orders');
        }
    
        public function broadcastAs()
        {
            return 'order.shipped';
        }
    }
    

2. Channel-Based Organization

  • Pattern: Group related events under channels (e.g., chat, notifications, orders).
  • Example:
    // Subscribe to multiple channels
    ekko.subscribe(['chat', 'notifications'], (message) => {
        console.log('Received:', message);
    });
    

3. Private Channels for Authenticated Users

  • Pattern: Use private channels for user-specific broadcasts (requires authentication middleware).
  • Example:
    class PrivateMessageSent extends EkkoBroadcastEvent
    {
        public $userId;
        public $message;
    
        public function __construct($userId, $message)
        {
            $this->userId = $userId;
            $this->message = $message;
        }
    
        public function broadcastOn()
        {
            return new PrivateChannel('user.' . $this->userId);
        }
    }
    
  • Frontend:
    ekko.subscribe('user.123', (message) => {
        console.log('Private message:', message);
    });
    

4. Presence Channels

  • Pattern: Track users' presence in a channel (e.g., for real-time collaboration tools).
  • Example:
    class UserJoinedRoom extends EkkoBroadcastEvent
    {
        public $roomId;
        public $userId;
    
        public function __construct($roomId, $userId)
        {
            $this->roomId = $roomId;
            $this->userId = $userId;
        }
    
        public function broadcastOn()
        {
            return new PresenceChannel('room.' . $this->roomId);
        }
    }
    
  • Frontend:
    ekko.subscribe('room.123', (message) => {
        console.log('Room update:', message);
    });
    
    // Join the presence channel
    ekko.join('room.123', { userId: 123, name: 'John' });
    

5. Integration with Laravel Echo

  • Pattern: Use Laravel Echo for a more Laravel-like experience (if you prefer).
  • Example: Install Echo:
    npm install --save laravel-echo pusher-js
    
    Configure resources/js/bootstrap.js:
    import Echo from 'laravel-echo';
    
    window.Pusher = require('pusher-js');
    
    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: process.env.MIX_PUSHER_APP_KEY,
        cluster: process.env.MIX_PUSHER_APP_CLUSTER,
        forceTLS: true,
        authEndpoint: '/broadcasting/auth',
    });
    
    Subscribe to Ekko channels via Echo:
    Echo.join(`ekko.${channelName}`)
         .here(users => console.log(users))
         .joining(user => console.log('joining:', user))
         .leaving(user => console.log('leaving:', user));
    

Integration Tips

1. Middleware for Private Channels

  • Ekko supports middleware for private channels. Create a middleware to validate user access:
    namespace App\Http\Middleware;
    
    use Closure;
    use EdwinLuijten\EkkoBroadcast\Middleware\BroadcastMiddleware;
    
    class AuthenticateEkko extends BroadcastMiddleware
    {
        public function handle($request, Closure $next)
        {
            if (!auth()->check()) {
                return false;
            }
            return $next($request);
        }
    }
    
  • Register the middleware in EkkoBroadcastServiceProvider:
    $this->app['ekko']->extend('private', function ($app) {
        return \EdwinLuijten\EkkoBroadcast\PrivateChannel::class;
    });
    
    $this->app['ekko.private.middleware']->append(AuthenticateEkko::class);
    

2. Customizing Broadcast Data

  • Override the broadcastWith method in your event to customize the payload:
    public function broadcastWith()
    {
        return [
            'message' => $this->message,
            'timestamp' => now()->toDateTimeString(),
            'user' => auth()->user()->only('id', 'name'),
        ];
    }
    

3. Fallback to Local Broadcasting

  • Use the log driver for development/testing:
    'driver' => env('APP_ENV') === 'local' ? 'log' : 'pusher',
    
  • View logs in storage/logs/laravel.log.

4. Testing Broadcasts

  • Mock the broadcaster in tests:
    $this->app->instance('ekko', \Mockery::mock('overload:EdwinLuijten\EkkoBroadcast\EkkoBroadcastManager'));
    
  • Assert broadcasts were sent:
    $broadcastMock->shouldReceive('broadcast')
        ->once()
        ->with('chat', 'Hello, world!');
    

Gotchas and Tips

Pitfalls

1. Deprecated Package

2. No Built-in Authentication

  • Issue: Ekko lacks built-in auth for private channels. You must implement middleware manually.
  • Tip: Use Laravel's BroadcastAuthorization trait or custom middleware (as shown above).

3. Limited Documentation

4. No Laravel Echo Support Out-of-the-Box

  • Issue: Ekko doesn’t integrate natively with Laravel Echo.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime