Skip to content

Current message pagination approach is not well-suited to a realtime chat application #324

@ndavidson7

Description

@ndavidson7

Currently, retrieving messages from a conversation uses offset-based pagination:

/**
* Get messages in conversation for the specific participant.
*
* @param Model $participant
* @param $paginationParams
* @param $deleted
*
* @return LengthAwarePaginator|HasMany|Builder
*/
private function getConversationMessages(Model $participant, $paginationParams, $deleted)
{
$messages = $this->messages()
->join($this->tablePrefix.'message_notifications', $this->tablePrefix.'message_notifications.message_id', '=', $this->tablePrefix.'messages.id')
->where($this->tablePrefix.'message_notifications.messageable_type', $participant->getMorphClass())
->where($this->tablePrefix.'message_notifications.messageable_id', $participant->getKey());
$messages = $deleted ? $messages->whereNotNull($this->tablePrefix.'message_notifications.deleted_at') : $messages->whereNull($this->tablePrefix.'message_notifications.deleted_at');
$messages = $messages->orderBy($this->tablePrefix.'messages.id', $paginationParams['sorting'])
->paginate(
$paginationParams['perPage'],
[
$this->tablePrefix.'message_notifications.updated_at as read_at',
$this->tablePrefix.'message_notifications.deleted_at as deleted_at',
$this->tablePrefix.'message_notifications.messageable_id',
$this->tablePrefix.'message_notifications.id as notification_id',
$this->tablePrefix.'message_notifications.is_seen',
$this->tablePrefix.'message_notifications.is_sender',
$this->tablePrefix.'messages.*',
],
$paginationParams['pageName'],
$paginationParams['page']
);
return $messages;
}

However, this is not the appropriate method for a realtime chat application. If a message is sent between the time that a user loads the first and second pages of messages, the offset will point to one of the previously retrieved messages. This is exactly the problem that cursor-based pagination aims to solve, not to mention better performance.

I believe the solution is as simple as changing

->paginate(

to ->cursorPaginate( and removing redundant pagination parameters.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions