musonza/chat

repository·master·Indexed 22 days ago

https://github.com/musonza/chat

A Laravel package for integrating a robust chat system into applications. It supports multiple models as participants via the Messageable trait, provides a fluent API for sending text and custom message types, and includes features such as cursor-based pagination, message reactions, conversation archiving, and AES-256-CBC encryption at rest. It supports private, public, and direct message (DM) conversation types.

Tokens
6K
Snippets
10
Records
42
Agent score
79%

What's inside musonza-chat

  1. Publish Chat assets and configuration

    master

    After installing the package, publish the database migrations and the musonza_chat.php configuration file to your Laravel config folder using the following command:

    php artisan vendor:publish --provider="Musonza\Chat\ChatServiceProvider"
  2. Configure and migrate the Chat database

    master

    Once the assets are published, run the migrations to create the necessary database tables for the chat system:

    php artisan migrate

    Configuration options can be found in config/musonza_chat.php.

  3. Enable message encryption at rest

    master

    You can encrypt message bodies using Laravel's built-in encryption (AES-256-CBC). To enable this, set 'encrypt_messages' => true in config/musonza_chat.php.

    Encryption is transparent: new messages are encrypted before storage, and decrypted automatically when retrieved. Existing unencrypted messages remain readable in a hybrid mode.

    Warning: Encryption uses your application's APP_KEY. If you change your APP_KEY, previously encrypted messages will become unreadable.

  4. Handle message encryption

    master
    The Message model supports automatic encryption of the message body. If Chat::shouldEncryptMessages() is enabled, the body attribute is automatically encrypted using Laravel's Crypt service when set, and decrypted when accessed. The model tracks this state via the is_encrypted boolean attribute.
  5. Install Musonza Chat in Laravel

    master

    Musonza Chat is a Laravel service provider. To set up the package, you need to publish its migrations and configuration files to your application.

    Use the following Artisan commands to publish the assets:

    Publish Migrations: php artisan vendor:publish --tag=chat.migrations

    Publish Configuration: php artisan vendor:publish --tag=chat.config

  6. Customize participant details in messages

    master

    When accessing the sender attribute on a Message, the system attempts to retrieve details from the participant's underlying model. You can customize what data is returned by implementing one of the following on your participant model (e.g., your User model):

    1. Define a getParticipantDetailsAttribute() accessor.
    2. Override the getParticipantDetails() method.

    If you do not provide a custom implementation, the system will return the participant's attributes, potentially filtered by Chat::senderFieldsWhitelist().

  7. Get messages with cursor pagination

    master

    For real-time chat, cursor-based pagination is recommended to prevent duplicate messages when new ones arrive. Use getMessagesWithCursor() and pass the next_cursor from the previous response into the cursor parameter of the next request.

    // Get first page
    $messages = Chat::conversation($conversation)
        ->setParticipant($participantModel)
        ->setCursorPaginationParams([
            'perPage' => 25,
            'sorting' => 'asc',
        ])
        ->getMessagesWithCursor();
    
    // Get next page using cursor from previous response
    $nextCursor = $messages->nextCursor()?->encode();
    
    $moreMessages = Chat::conversation($conversation)
        ->setParticipant($participantModel)
        ->setCursorPaginationParams([
            'perPage' => 25,
            'sorting' => 'asc',
            'cursor' => $nextCursor,
        ])
        ->getMessagesWithCursor();
  8. Send text and custom type messages

    master

    Use the Chat::message() fluent API to send messages. The default type is text. You can specify a custom type() (e.g., image, attachment) and provide additional metadata using data().

    // Send a text message
    $message = Chat::message('Hello')
                ->from($model)
                ->to($conversation)
                ->send();
    
    // Send a message with a custom type
    $message = Chat::message('http://example.com/img')
    	->type('image')
    	->from($model)
    	->to($conversation)
    	->send();
    
    // Send a message with custom data (e.g., attachments)
    $message = Chat::message('Attachment 1')
    	->type('attachment')
    	->data(['file_name' => 'post_image.jpg', 'file_url' => 'http://example.com/post_img.jpg'])
    	->from($model)
    	->to($conversation)
    	->send();
  9. Customize participant details via Accessors

    master

    The package uses getParticipantDetails() to represent participants in a uniform way. By default, it returns an array containing a name column. You can customize this by adding an Eloquent Accessor getParticipantDetailsAttribute to your model to return any custom array structure.

    public function getParticipantDetailsAttribute()
    {
        return [
            'name' => $this->someValue,
            'foo' => 'bar',
        ];
    }
  10. Archive and unarchive conversations

    master

    Archiving is per-participant. One user can archive a thread without affecting others. By default, archived conversations are excluded from a participant's listings. A new incoming message automatically unarchives the recipient (this behavior can be disabled in config/musonza_chat.php via unarchive_on_new_message => false).

    // Archive / unarchive for a single participant via Chat facade
    Chat::conversation($conversation)->setParticipant($participantModel)->archive();
    Chat::conversation($conversation)->setParticipant($participantModel)->unarchive();
    
    // Or directly on the model
    $conversation->archive($participantModel);
    $conversation->unarchive($participantModel);
    
    // Listing conversations
    // Default: excludes archived
    Chat::conversations()->setParticipant($participantModel)->get();
    
    // Show only archived
    Chat::conversations()->setParticipant($participantModel)->archived()->get();
    
    // Show both
    Chat::conversations()->setParticipant($participantModel)->withArchived()->get();