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 Bundle Laravel Package

btba/chat-bundle

Symfony bundle providing a simple chat service with configurable refresh interval and Doctrine entities for authors and messages. Install via Composer, register the bundle, add YAML config and routes, and extend base models to persist chat data.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require btba/chat-bundle
    

    Register the bundle in config/bundles.php:

    Btba\ChatBundle\BtbaChatBundle::class => ['all' => true]
    
  2. Configuration: Create config/packages/btba_chat.yaml:

    btba_chat:
        update_interval: 1000
        message_class: App\Entity\ChatMessage
        author_class: App\Entity\User
    
  3. Routes: Add to config/routes/btba_chat.yaml:

    btba_chat:
        resource: '@BtbaChatBundle/Resources/config/routes.yaml'
        prefix: /chat
    
  4. Entities: Extend BaseAuthor and BaseChatMessage in your User and ChatMessage entities (see README).

  5. Repository: Add MessageQuery trait to your ChatMessageRepository.

  6. Assets: Import CSS/JS in app.css/app.js:

    @import '../../vendor/btba/chat-bundle/assets/css/chat.css';
    
    import * as chat from '../../vendor/btba/chat-bundle/assets/js/chat';
    
  7. Render Chat: Add to your Twig template:

    {{ render(controller('Btba\\ChatBundle\\Controller\\ChatController::show')) }}
    

Implementation Patterns

Core Workflow

  1. Real-Time Updates: The update_interval (default: 1000ms) controls how often the chat polls for new messages. Use AJAX to fetch updates via the bundle’s API (e.g., /chat/messages).

  2. Message Handling:

    • Sending Messages: Use the submitChat JS function to POST messages to /chat/send. Example:
      chat.submitChat(e, { content: "Hello!", authorId: 1 });
      
    • Displaying Messages: The bundle renders messages via Twig. Extend the template (resources/views/chat/index.html.twig) to customize rendering.
  3. User Integration:

    • Authenticate users via Symfony’s security system (e.g., {{ app.user }} in Twig).
    • Pass the current user’s ID to JS for message attribution:
      chat.setCurrentUser({{ app.user.id }});
      
  4. Database Operations:

    • Use ChatMessageRepository to query messages (e.g., findByDate()).
    • Example query in a controller:
      $messages = $this->getDoctrine()
          ->getRepository('App:ChatMessage')
          ->findBy([], ['date' => 'ASC']);
      
  5. Event Listeners: Trigger custom logic on message creation by extending the bundle’s events (e.g., MessageSentEvent). Override the bundle’s event dispatcher in your services.yaml:

    services:
        App\EventListener\ChatListener:
            tags:
                - { name: kernel.event_listener, event: btba_chat.message_sent, method: onMessageSent }
    

Integration Tips

  • Frontend Frameworks: Replace jQuery with Vue/React by rewriting chat.js to use your framework’s HTTP client (e.g., axios). Example Vue integration:

    methods: {
       sendMessage() {
         axios.post('/chat/send', { content: this.message, authorId: this.userId })
           .then(response => this.messages.push(response.data));
       }
     }
    
  • WebSockets: Replace polling with Mercure or Pusher by extending the ChatController to broadcast messages via WebSocket.

  • Permissions: Restrict message access in ChatController:

    public function showAction(Request $request)
    {
        $this->denyAccessUnlessGranted('CHAT_VIEW', $request->getUser());
        // ...
    }
    
  • Testing: Mock the MessageQuery trait in PHPUnit:

    $repository = $this->createMock(ChatMessageRepository::class);
    $repository->method('findByDate')->willReturn([$mockMessage]);
    $this->container->set('App:ChatMessage', $repository);
    

Gotchas and Tips

Pitfalls

  1. Entity Mismatch:

    • Error: Class "App\Entity\ChatMessage" is not a valid entity or extends BaseChatMessage.
    • Fix: Ensure your ChatMessage extends Btba\ChatBundle\Model\BaseChatMessage and includes all required fields (content, date, author).
  2. Route Conflicts:

    • Error: No route found for "GET /chat".
    • Fix: Verify the prefix in btba_chat.yaml matches your routes file and is loaded after other bundles.
  3. JavaScript Errors:

    • Error: chat is not defined.
    • Fix: Ensure chat.js is imported after jQuery (if used) and the DOM is ready:
      document.addEventListener('DOMContentLoaded', () => {
          import * as chat from '...';
      });
      
  4. Polling Overhead:

    • Issue: High update_interval causes lag or excessive DB queries.
    • Fix: Increase the interval (e.g., 3000) or implement server-sent events (SSE).
  5. Circular Dependencies:

    • Error: Class "App\Entity\User" uses a non-existent property "messages".
    • Fix: Add bidirectional relationships in both entities:
      // User.php
      private $messages;
      // ChatMessage.php
      private $author;
      

Debugging

  • Log Messages: Enable Symfony’s profiler to inspect ChatController responses:

    // config/packages/dev/btba_chat.yaml
    btba_chat:
        debug: true
    
  • Database Queries: Use Doctrine’s query logging:

    $this->getDoctrine()->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    
  • Event Debugging: Dump events in a listener:

    public function onMessageSent(MessageSentEvent $event) {
        dump($event->getMessage());
    }
    

Extension Points

  1. Custom Templates: Override the default Twig template by copying BtbaChatBundle:Chat:index.html.twig to templates/chat/index.html.twig.

  2. Message Validation: Extend the bundle’s validator by adding constraints to your ChatMessage entity:

    use Symfony\Component\Validator\Constraints as Assert;
    
    /**
     * @Assert\NotBlank
     * @Assert\Length(max=1000)
     */
    protected $content;
    
  3. API Endpoints: Add custom endpoints by extending ChatController:

    class CustomChatController extends ChatController {
        public function customAction() {
            return $this->json(['status' => 'ok']);
        }
    }
    

    Register the route in btba_chat.yaml:

    custom_chat:
        path: /chat/custom
        controller: App\Controller\CustomChatController::customAction
    
  4. Message Storage: Replace Doctrine with another ORM (e.g., MongoDB) by implementing MessageQuery for your repository.

  5. UI Components: Replace the default chevron/toggle logic by extending the chat.js module:

    chat.changeChevron = function(element) {
        // Custom logic
    };
    
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope