{{-- Incremental chat updates rendered by process@updateMessages. Two important fixes vs the original template: 1. The original overwrote the loop-control variable `$sender_type` inside the first iteration (e.g. `$sender_type = $msg->getCustomer->name`). After that, the `if ($sender_type=='customer')` branch no longer matched, so every message *after the first* in a polled batch rendered on the wrong side of the conversation. We keep the viewer role in `$viewer` and write the display name into a separate `$displayName` so the branch decision stays stable across iterations. 2. `$msg->getSender` / `$msg->getCustomer` can return null if the related user record was hard-deleted (e.g. via changeCustomerStatus rejection, or an employee being removed). Dereferencing ->name on null 500'd the AJAX response, silently killing the chat polling loop. We fall back to 'User' when the relation is missing. --}} @php $viewer = $sender_type; // 'customer' or an aico role @endphp @foreach ($messages as $msg) @php $senderName = optional($msg->getSender)->name ?? 'User'; $customerName = optional($msg->getCustomer)->name ?? 'User'; if ($viewer === 'customer') { // Viewed from the customer's side. if ((string) $msg->receiver_type === '0') { // Outgoing (customer -> AICO). $type = 'sender'; $displayName = explode(' ', $customerName)[0]; } else { // Incoming (AICO -> customer). $type = 'receiver'; $displayName = explode(' ', $senderName)[0]; } } else { // Viewed from an AICO employee's side. if ((string) $msg->receiver_type === '0') { // Incoming (customer -> AICO). $type = 'receiver'; $displayName = explode(' ', $senderName)[0]; } else { // Outgoing (AICO -> customer), shown as ours. $type = 'sender'; $displayName = explode(' ', $senderName)[0]; } } @endphp