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

Filament Chat Laravel Package

zedmagdy/filament-chat

Filament v4+ chat plugin for Laravel: configurable chat sources, 1:1 and group conversations, text + file attachments via Spatie Media Library, read/unread tracking, search, and real-time updates via polling or broadcasting (Reverb/Pusher).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require zedmagdy/filament-chat
    php artisan vendor:publish --tag="filament-chat-migrations"
    php artisan migrate
    php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="medialibrary-migrations"
    php artisan migrate
    
  2. Add HasChats trait to your User model:

    use ZEDMagdy\FilamentChat\Traits\HasChats;
    
  3. Create a chat source (quickest via Artisan):

    php artisan make:chat-source Staff --model=User
    
  4. Register the plugin in your PanelProvider:

    ->plugin(FilamentChatPlugin::make()->sources([StaffChatSource::class]))
    

First Use Case

Create a staff-to-staff chat system:

  • Users can start new conversations via the + button in the Filament sidebar.
  • Messages appear in real-time (polling by default).
  • Attach files using Filament’s built-in file uploader.

Implementation Patterns

Core Workflows

1. Chat Source Setup

  • Single Source: Use make:chat-source for a quick start (e.g., StaffChat).
  • Multiple Sources: Register each source in the plugin:
    FilamentChatPlugin::make()
        ->sources([
            StaffChatSource::class,
            SupportChatSource::class,
        ])
    
  • Aggregate Sources: Combine multiple sources into a unified inbox:
    ->aggregates([AllMessagesAggregateChatSource::class])
    

2. UI Integration

  • Default UI: The package provides a ready-to-use chat sidebar and conversation view.
  • Customization:
    • Publish views: php artisan vendor:publish --tag="filament-chat-views".
    • Override Blade templates (e.g., filament-chat::components.chat-sidebar).

3. Programmatic Conversations

  • Direct Chats:
    $conversation = Conversation::create(['source' => 'staff', 'type' => 'direct']);
    Participant::create([...]); // Add participants
    
  • Group Chats:
    $group = Conversation::create(['source' => 'staff', 'type' => 'group', 'name' => 'Team']);
    
  • Messages:
    Message::create([
        'conversation_id' => $conversation->id,
        'senderable_id' => $user->id,
        'body' => 'Hello!',
    ]);
    

4. Attachments

  • Use Spatie Media Library:
    $message->addMedia($file)->toMediaCollection('chat-attachments');
    
  • Configure allowed file types in config/filament-chat.php:
    'attachments' => [
        'accepted_types' => ['image/jpeg', 'application/pdf', ...],
    ],
    

5. Real-Time Updates

  • Polling (Default): Configure interval in .env:
    FILAMENT_CHAT_REALTIME_MODE=polling
    FILAMENT_CHAT_POLLING_INTERVAL=5s
    
  • Broadcasting (Reverb/Pusher): Set mode to broadcasting and ensure Laravel broadcasting is configured. Events (MessageSent, MessagesRead) auto-broadcast to chat.conversation.{id}.

Integration Tips

Filament Panel

  • Navigation: Chat sources appear in Filament’s sidebar by default. Customize via:
    public function getNavigationGroup(): ?string { return 'Communication'; }
    public function getNavigationSort(): ?int { return 1; }
    
  • Permissions: Use Filament’s built-in policies to restrict access:
    ->middleware([...])
    ->permission('view-chats')
    

Eloquent Relationships

  • Leverage HasChats trait for user-specific queries:
    $user->conversations()->where('source', 'staff')->get();
    $user->sentMessages()->latest()->take(10)->get();
    

Testing

  • Unit Tests: Mock ChatSource and Message models.
  • Feature Tests: Use Filament’s testing helpers:
    $this->actingAs($user)
         ->get('/admin/chat/staff')
         ->assertSee('Chat');
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts:

    • Run filament-chat migrations after Spatie Media Library migrations.
    • If using custom table prefixes, update config/filament-chat.php:
      'table_prefix' => 'custom_chat_',
      
  2. Real-Time Issues:

    • Broadcasting: Ensure your Laravel broadcasting driver (Reverb/Pusher) is running.
    • Polling: High intervals (e.g., 10s) may feel laggy; test with 5s or lower.
    • Debugging: Check Laravel logs for BroadcastFailed events.
  3. Attachment Limits:

    • Default max files: 4 (configurable in config/filament-chat.php).
    • Large files may fail silently; validate client-side:
      // Example: Check file size before upload
      if (file.size > 10 * 1024 * 1024) { // 10MB
          alert('File too large');
      }
      
  4. Participant Filtering:

    • getAvailableParticipantsQuery() excludes the current user automatically, but ensure your query logic accounts for this:
      // Bad: May return the current user
      User::where('role', 'staff')->get();
      // Good: Explicitly exclude
      User::where('role', 'staff')->where('id', '!=', auth()->id())->get();
      
  5. Group Chat Quirks:

    • Group conversations require allowsGroupChats() to return true.
    • Group names must be unique per source; validate server-side:
      public function rules(): array {
          return [
              'name' => ['required', Rule::unique(Conversation::class)->where('source', $this->source)->where('type', 'group')],
          ];
      }
      

Debugging Tips

  1. Log Chat Events: Add a registering callback to models for debugging:

    Message::observe(function ($message) {
        \Log::debug('Message created', ['id' => $message->id, 'body' => $message->body]);
    });
    
  2. Check Broadcast Channels: Verify channels are authorized in app/Providers/BroadcastServiceProvider:

    Broadcast::channel('chat.conversation.{id}', function ($user, $conversation) {
        return $conversation->participants()->where('participantable_id', $user->id)->exists();
    });
    
  3. UI Glitches:

    • Clear Filament’s cache if styles don’t update:
      php artisan filament:cache:clear
      
    • Disable JavaScript bundling in development for faster iteration:
      MIX_APP_URL=http://localhost:8000
      

Extension Points

  1. Custom Message Types: Extend the Message model to add metadata (e.g., is_urgent):

    class CustomMessage extends Message {
        protected $casts = [
            'is_urgent' => 'boolean',
        ];
    }
    

    Update config:

    'models' => [
        'message' => CustomMessage::class,
    ],
    
  2. Custom Chat Sources: Add logic to filter conversations dynamically:

    public function getConversationsQuery(): Builder {
        return parent::getConversationsQuery()->whereHas('messages', function ($query) {
            $query->where('body', 'like', '%urgent%');
        });
    }
    
  3. Real-Time Extensions: Listen to custom events in your frontend:

    import Echo from 'laravel-echo';
    
    const echo = new Echo({
        broadcaster: 'pusher',
        key: process.env.MIX_PUSHER_APP_KEY,
    });
    
    echo.private(`chat.conversation.${conversationId}`)
         .listen('CustomMessageEvent', (data) => {
             console.log('Custom event:', data);
         });
    
  4. API Endpoints: Expose chat data via Laravel API routes:

    Route::get('/api/chats/{source}', [ChatController::class, 'index']);
    

    Use the same Conversation and Message models for consistency.

  5. Webhook Triggers: Dispatch events when messages are sent:

    Message::created(function ($message) {
        event(new MessageSent($message));
    });
    

    Listen

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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony