Return last page from a Paginator

When building a forum app, I faced the use case where I needed to return the last discussion page posts.
To be precise: if a discussion displays 10 posts by page and the discussion has 48 posts, I want the 41-48nth posts which corresponds to the discussion's 5th page.

Because I didn't want to load all the posts and then filter them using PHP, I preferred to use an additional count query and then use the Laravel Paginator:

$discussion = Discussion::find(4);
$postsPerDiscussionPage = $discussion->posts()->getRelated()->getPerPage();

$lastPage = ceil($discussion->posts()->count() / $postsPerDiscussionPage);

$posts =
    Post::query()
        ->where($discussion->getForeignKey(), $discussion->id)
        ->paginate(null, ['*'], 'page', $lastPage);

Using PHP8 Syntax avoids some verbosity on the query paginate method:

$posts =
    Post::query()
        ->where($discussion->getForeignKey(), $discussion->id)
        ->paginate(page: $lastPage);

Comments

Be the first to post a comment!

Add a comment

Preview