Skip to content

Instantly share code, notes, and snippets.

@jesseschutt
Created June 18, 2021 20:53
Show Gist options
  • Save jesseschutt/53f9bc114ee41b598ab698a9bc47ed9d to your computer and use it in GitHub Desktop.
Save jesseschutt/53f9bc114ee41b598ab698a9bc47ed9d to your computer and use it in GitHub Desktop.
$reallyOldUnreadMessage = factory(Message::class)->create([
'created_at' => now()->subMinutes(37)
]);
$oldUnreadMessage = factory(Message::class)->create([
'created_at' => now()->subMinutes(36)
]);
$recentMessage1 = factory(Message::class)->create([
'created_at' => now()->subMinutes(20)
]);
$latestMessage = factory(Message::class)->create([
'created_at' => now()->subMinutes(16)
]);
// 1) If the user's most recent unread message is older than $minutes (15 is default)
// 2) Check if the previous message is unread and within $minutes
// 3) -> repeat 2) until no more unread messages match criteria
$unreadMessages = $channel->messages()
->where('created_at', '<', now()->subMinutes($minutes))
->whereNull('participants_read_status->' . $user->getUuid())
->latest()
->get();
$tooOld = false;
$messages = $unreadMessages->filter(function(Message $message, $index) use ($unreadMessages, $minutes, &$tooOld) {
// Always return the first message as it is legit based on the initial query
if ($index === 0) {
return true;
}
// Exit if we have determined one message is more than 15 minutes older than the rest
if ($tooOld) {
return false;
}
// Check if the next closest message is within 15 minutes
if ($unreadMessages[$index - 1]->created_at->diffInMinutes($message->created_at) < $minutes) {
return $tooOld = true;
}
// Filter out the rest
return false;
});
return $messages->values();
@jesseschutt
Copy link
Author

This is working but seems kind of loose.

The result should contain $latestMessage and $recentMessage1 while filtering out the older unread messages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment