Skip to content

Chatable ​

Namespace: Unusualify\Modularous\Entities\Traits\Chatable

Gives every model its own Chat thread with full message history, read status tracking, unread counts, and notification dispatch. Uses ChatableScopes for query filtering.


Boot Behavior ​

EventAction
retrievedSets _chat_id attribute if chat exists; creates a Chat record if the model is persisted and has no chat
createdCreates the initial Chat record
savingRemoves _chat_id from dirty attributes

Relationships ​

php
public function chat(): MorphOne                          // → Chat (auto-created)
public function chatMessages(): HasManyThrough            // → ChatMessage through Chat
public function creatorChatMessages(): HasManyThrough     // → ChatMessages sent by the model's creator
public function latestChatMessage(): HasOneThrough        // → Single most recent ChatMessage
public function unreadChatMessages(): HasManyThrough      // → Unread messages (is_read = false)
public function unreadChatMessagesForYou(): HasManyThrough // → Unread messages not authored by current user
public function unreadChatMessagesFromClient(): HasManyThrough
public function unreadChatMessagesFromCreator(): HasManyThrough

Methods ​

MethodSignatureDescription
truncateChat(): voidDeletes and recreates the chat thread (clears all messages)
handleChatableNotification(): voidDispatches an UnreadChatMessage event and sends a ChatableUnreadNotification if the latest message is unread and has been waiting longer than $chatableNotificationInterval minutes
numberOfChatMessages(): intCount of all chat messages
numberOfUnreadChatMessages(): intCount of unread messages
numberOfUnreadChatMessagesForYou(): intCount of unread messages not authored by current user
numberOfUnreadChatMessagesFromCreator(): intCount of unread messages from the record's creator
numberOfUnreadChatMessagesFromClient(): intCount of unread messages from client-role users
numberOfUnansweredCreatorChatMessages(): intReturns 1 if the latest message is from the creator and unread, else 0

Computed Attributes ​

AttributeDescription
chat_messages_countTotal message count
unread_chat_messages_countUnread message count
unread_chat_messages_for_you_countUnread messages not from current user
unread_chat_messages_from_creator_countUnread messages from the record's creator

Configuration ​

PropertyTypeDefaultDescription
$chatableNotificationIntervalint60Minutes before a notification is re-dispatched for an unanswered message

Usage ​

php
use Unusualify\Modularous\Entities\Traits\Chatable;

class Order extends Model
{
    use Chatable;
}

// Chat record (auto-created)
$order->chat;

// Messages
$order->chatMessages()->latest()->get();
$order->latestChatMessage;
$order->unreadChatMessages()->count();

// Counts
$order->numberOfUnreadChatMessages();
$order->chat_messages_count;

// Clear chat history
$order->truncateChat();

// Dispatch notification if needed
$order->handleChatableNotification();