@if (!empty($users))
@php
// Sort the chats by created_at or updated_at timestamp in descending order
$latestChat = $chats->sortByDesc('created_at')->first();
$latestUser = null;
$displayedUsers = [];
// Find the user related to the latest chat
if ($latestChat) {
$latestUser = $users->firstWhere('id', $latestChat->sender_id) ?: $users->firstWhere('id', $latestChat->receiver_id);
}
@endphp
@if ($latestUser)
@php
// Add the latest user to the displayedUsers array to avoid duplication later
$displayedUsers[] = $latestUser->id;
@endphp