This may or may not help but have a look:
https://gist.github.com/vluzrmos/3ce756322702331fdf2bf414fea27bcb
It's helped others:
https://laracasts.com/discuss/channels/laravel/how-to-paginate-laravel-collection
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
On my website, I have Submissions, and submissions can have comments.
Comments can have upvotes and downvotes, leading to a total "score" for the comment.
In this example, before passing the comments to the view, I sort them by score.
$comments = Comment::where('submission_id', $submission->id)->where('parent_id', NULL)->get();
$comments = $comments->sortByDesc(function($comment){
return count($comment['upvotes']) - count($comment['downvotes']);
});
This works fine. The higher the score of a comment, the higher it is sorted.
However, I want to paginate these results.
If I do ->paginate(10) instead get(), the following sortByDesc will only sort those 10 results.
So logically I would want to add the paginator after the sortByDesc like so:
$comments = $comments->sortByDesc(function($comment){
return count($comment['upvotes']) - count($comment['downvotes']);
})->paginate(10);
However this will return the error:
Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
as expected.
My question is, what is the alternative to using paginate in this situation?
Please or to participate in this conversation.