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

Chat Laravel Package

unseen-codes/chat

Plug-and-play Livewire single-file chat component for Laravel. Drop livewire:chat-box anywhere for 1-on-1 or group chats with reactions, replies, attachments, read receipts, typing indicator, editing, soft deletes, and fully config-driven features/models.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Chat

  1. Install & Publish Run composer require unseen-codes/chatphp artisan vendor:publish --tag=chat-configphp artisan vendor:publish --tag=chat-migrationsphp artisan migrate. Verify: Check config/chat.php for feature toggles (e.g., emoji_reactions, file_attachments).

  2. Add Trait to User Model Append use UnseenCodes\Chat\Traits\Chattable; to app/Models/User.php. Note: The package auto-creates chats() and messages() relationships.

  3. Drop the Component Place <livewire:chat-box /> in any Blade view (e.g., resources/views/chat.blade.php). First Test: Visit the page as an authenticated user—you’ll see an empty chat list.

  4. Trigger a Conversation Use the package’s helper:

    use UnseenCodes\Chat\Facades\Chat;
    Chat::startConversation([$userId1, $userId2]); // 1-on-1
    Chat::startGroupConversation([$userId1, $userId2, $userId3]); // Group
    

    Where to call it? In a Livewire component’s mount() or a controller (if not using Livewire/Volt routes).


Implementation Patterns

Core Workflows

  1. Embedding in Layouts

    • Use <livewire:chat-box /> in a sidebar or modal (e.g., resources/views/layouts/app.blade.php).
    • Pass context via Livewire props:
      <livewire:chat-box :participants="[$user->id, $friend->id]" />
      
    • Pro Tip: Cache the component if used globally (e.g., wire:key="chat-sidebar-{auth()->id()}").
  2. Customizing Conversation Triggers

    • Button-initiated chats:
      <button wire:click="startChat({{ $user->id }})">Message</button>
      
      In the Livewire component:
      public function startChat(int $userId) {
          Chat::startConversation([auth()->id(), $userId]);
      }
      
    • URL-based chats: Add a route like Route::get('/chat/{user}', [ChatController::class, 'show']) and pass the ID to the component.
  3. Handling Attachments

    • Configure allowed MIME types in config/chat.php under file_attachments.
    • Use the built-in file picker:
      <livewire:chat-box :allowed-mimes="['image/jpeg', 'application/pdf']" />
      
    • Workflow: Drag files into the chat input area or use the paperclip icon.
  4. Real-Time Features

    • Typing Indicators: Auto-enabled (configurable via typing_indicator_timeout).
    • Read Receipts: Toggle with read_receipts in config. Track with:
      $message->readBy()->contains(auth()->id()); // Check if current user read
      
  5. Threaded Replies

    • Reply to a message by clicking the reply button (UI handles threading).
    • Query threads with:
      $message->replies()->with('author')->get();
      

Integration Tips

  • Volt Pages: Replace <livewire:chat-box /> with @chat in Volt templates.
  • API Endpoints: Use the Chat facade to fetch conversations:
    $conversations = Chat::conversations()->whereHas('participants', fn($q) => $q->where('users.id', auth()->id()))->get();
    
  • Notifications: Extend the MessageSent event (published by the package) to trigger Pusher/broadcasts:
    use UnseenCodes\Chat\Events\MessageSent;
    MessageSent::dispatch($message)->toOthers(); // Broadcast to all participants except sender
    

Gotchas and Tips

Pitfalls

  1. Model Relationships

    • Issue: Forgetting to add Chattable trait to the User model breaks all chat functionality.
    • Fix: Run php artisan optimize:clear after adding the trait.
  2. Livewire Key Conflicts

    • Issue: Multiple <livewire:chat-box /> instances on one page may cause state conflicts.
    • Fix: Use unique wire:key (e.g., wire:key="chat-{conversationId}").
  3. File Storage Paths

    • Issue: Attachments default to storage/app/public/chat. Override in config:
      'file_attachments' => [
          'disk' => 's3',
          'path' => 'chat-files',
      ],
      
    • Gotcha: Ensure the disk is configured in config/filesystems.php.
  4. Soft Deletes

    • Issue: Messages marked as soft-deleted may reappear if not filtered.
    • Fix: Always scope queries:
      $messages = Message::withTrashed()->where('conversation_id', $id)->get();
      
  5. Participant Sync

    • Issue: Manually adding participants to a conversation via Chat::addParticipant() doesn’t update the UI.
    • Fix: Use Livewire’s refresh() or emit an event:
      $this->emit('chat-participants-updated', $conversationId);
      

Debugging

  • Log Messages: Enable debug mode in config/chat.php:

    'debug' => env('APP_DEBUG', false),
    

    Logs appear in storage/logs/laravel.log.

  • Wire:Model Events: Listen for Livewire model events to debug state:

    $this->dispatchBrowserEvent('chat-debug', ['message' => 'Test']);
    

Extension Points

  1. Custom Models

    • Override default models in config/chat.php:
      'models' => [
          'user' => App\Models\CustomUser::class,
          'conversation' => App\Models\CustomConversation::class,
      ],
      
    • Note: Ensure the custom models include the Chattable trait.
  2. Message Events

    • Extend the Message model to add custom fields:
      class Message extends \UnseenCodes\Chat\Models\Message
      {
          protected $casts = [
              'is_pinned' => 'boolean',
          ];
      }
      
    • Add a migration to update the table schema.
  3. UI Customization

    • Override the Livewire component by publishing views:
      php artisan vendor:publish --tag=chat-views
      
    • Modify resources/views/vendor/chat-box.blade.php to change styles/structure.
    • Pro Tip: Use Tailwind classes or inline styles for rapid theming.
  4. Rate Limiting

    • Add middleware to throttle chat actions (e.g., prevent spam):
      Route::middleware(['throttle:10,1'])->group(function () {
          // Chat routes
      });
      
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.
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
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