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

Ti Ext Broadcast Laravel Package

tastyigniter/ti-ext-broadcast

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup Steps

  1. Install the Package
    composer require tastyigniter/ti-ext-broadcast
    
  2. Publish Configuration
    php artisan vendor:publish --provider="TastyIgniter\Broadcast\BroadcastServiceProvider"
    
  3. Configure .env
    BROADCAST_DRIVER=pusher  # or 'redis', 'ably', etc.
    MIX_PUSHER_APP_KEY=your_app_key
    MIX_PUSHER_APP_CLUSTER=your_cluster
    
  4. First Broadcast Event Create a TastyIgniter-compatible event (e.g., app/Events/OrderStatusUpdated.php):
    namespace App\Events;
    
    use Illuminate\Broadcasting\Channel;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Queue\SerializesModels;
    
    class OrderStatusUpdated implements ShouldBroadcast
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
    
        public $order;
    
        public function __construct($order)
        {
            $this->order = $order;
        }
    
        public function broadcastOn()
        {
            return new Channel('orders.' . $this->order->id);
        }
    
        public function broadcastAs()
        {
            return 'order.status.updated';
        }
    }
    
  5. Trigger the Event Dispatch in a TastyIgniter controller/service:
    use App\Events\OrderStatusUpdated;
    
    // Inside a method (e.g., after updating order status)
    event(new OrderStatusUpdated($order));
    
  6. Frontend Listener (JavaScript) Add to your resources/js/app.js:
    import Echo from 'laravel-echo';
    
    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: process.env.MIX_PUSHER_APP_KEY,
        cluster: process.env.MIX_PUSHER_APP_CLUSTER,
        forceTLS: true
    });
    
    Echo.channel('orders.123')  // Replace with dynamic channel
        .listen('order.status.updated', (data) => {
            new Notification(`Order #${data.order.id} updated to ${data.order.status}`).show();
        });
    

Where to Look First

  • Documentation: TastyIgniter Broadcast Docs
  • Example Events: Check vendor/tastyigniter/ti-ext-broadcast/src/Events/ for TastyIgniter-specific event templates.
  • Config File: config/ti-ext-broadcast.php for driver-specific settings (e.g., Redis queue, Pusher options).
  • Service Provider: TastyIgniter\Broadcast\BroadcastServiceProvider for bootstrapping logic.

First Use Case

Live Order Status Updates

  1. Extend Order model to dispatch OrderStatusUpdated on status changes.
  2. Listen for updates in the frontend to show toast notifications or update a live dashboard.
  3. Test with a single order to verify real-time updates.

Implementation Patterns

Core Workflows

1. Event-Driven Broadcasting

  • Pattern: Use Laravel’s ShouldBroadcast interface for all events requiring real-time updates.
  • Example:
    class ReservationConfirmed implements ShouldBroadcast
    {
        use Dispatchable, SerializesModels;
    
        public $reservation;
    
        public function broadcastOn()
        {
            return new PrivateChannel('reservations.' . $this->reservation->user_id);
        }
    }
    
  • Integration Tip: Leverage TastyIgniter’s Event facade or Event::dispatch() for consistency.

2. Channel Organization

  • Pattern: Use hierarchical channels (e.g., users.{user_id}.notifications) for scalability.
  • Example:
    public function broadcastOn()
    {
        return new Channel('users.' . auth()->id() . '.alerts');
    }
    
  • Tip: Avoid overly broad channels (e.g., public.notifications) to minimize unnecessary connections.

3. Frontend Subscription Management

  • Pattern: Dynamically subscribe to channels based on user context (e.g., current page, auth status).
  • Example:
    // Subscribe only on the "Orders" page
    if (window.location.pathname.includes('/orders')) {
        Echo.join(`users.${userId}.orders`)
             .here((users) => { /* Update UI */ })
             .joining((user) => { /* Handle new user */ });
    }
    

4. Fallback Mechanisms

  • Pattern: Combine broadcasts with queued jobs for reliability.
  • Example:
    event(new OrderPlaced($order));
    OrderNotification::dispatch($order)->delay(now()->addSeconds(5)); // Fallback email/SMS
    

5. TastyIgniter-Specific Extensions

  • Pattern: Extend TastyIgniter’s core models (e.g., Order, User) to auto-broadcast events.
  • Example:
    namespace App\Models;
    
    use TastyIgniter\Broadcast\Traits\BroadcastsEvents;
    
    class Order extends Model
    {
        use BroadcastsEvents;
    
        protected $dispatchesEvents = [
            'updated' => ['App\Events\OrderStatusUpdated'],
        ];
    }
    

Integration Tips

Laravel Broadcasting Drivers

Driver Use Case Configuration Tip
Pusher Quick setup, managed service Use BROADCAST_DRIVER=pusher in .env.
Redis Self-hosted, cost-effective Requires Redis server; use BROADCAST_DRIVER=redis.
Reverb Laravel-native alternative to Pusher Added in v4.0.5; configure via .env.
Ably Global low-latency Requires Ably account; set BROADCAST_DRIVER=ably.

Frontend Libraries

  • Laravel Echo: Required for all broadcasts. Install via:
    npm install --save laravel-echo pusher-js
    
  • Service Workers: For push notifications (optional). Use libraries like workbox or Push.js.

Testing Strategies

  1. Unit Tests: Mock the broadcaster to test event serialization.
    $event = new OrderPlaced($order);
    $this->assertEquals('order.placed', $event->broadcastAs());
    
  2. Integration Tests: Use Laravel’s BroadcastServiceProvider to verify broadcasts.
    $this->artisan('event:generate')
         ->expectsOutput('OrderPlaced')
         ->assertExitCode(0);
    
  3. E2E Tests: Simulate WebSocket connections with tools like pusher-js or socket.io-client.

Performance Optimization

  • Channel Pruning: Unsubscribe from channels when no longer needed (e.g., on route change).
    Echo.leave(`users.${userId}.notifications`);
    
  • Debounce Events: Throttle rapid-fire events (e.g., typing events) to reduce broadcast load.
    let typingTimer;
    Echo.channel('chat.room')
        .listen('typing', () => {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(() => { /* Handle */ }, 500);
        });
    

Gotchas and Tips

Common Pitfalls

1. Frontend Not Receiving Broadcasts

  • Cause: Missing window.Pusher or window.Echo initialization.
  • Fix: Ensure resources/js/app.js includes:
    import Pusher from 'pusher-js';
    window.Pusher = Pusher;
    
  • Debug Tip: Check browser console for Pusher errors (e.g., invalid APP_KEY).

2. Private Channels Failing

  • Cause: Laravel Sanctum/Passport not configured for private channels.
  • Fix: Ensure .env has:
    SANCTUM_STATEFUL_DOMAINS=your-app.test
    
  • Debug Tip: Verify CSRF token is included in Echo initialization:
    Echo.auth({
        headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }
    });
    

3. Redis Broadcasts Not Working

  • Cause: Redis queue not running or misconfigured.
  • Fix: Start Redis server and ensure .env has:
    QUEUE_CONNECTION=redis
    BROADCAST_CONNECTION=redis
    
  • Debug Tip: Check Laravel logs for Redis::connect() errors.

4. Events Not Broadcasting

  • Cause: Missing ShouldBroadcast interface or incorrect broadcastOn().
  • Fix: Verify the event
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor