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?
EDIT:
When trying the response of @party-ring (and switching the double quotes and single quotes) I get the following error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '["upvotes"]) - count($comment["downvotes"]) desc limit 10 offset 0' at line 1 (SQL: select * from
comments
wheresubmission_id
= 1 andparent_id
is null order by count($comment["upvotes"]) - count($comment["downvotes"]) desc limit 10 offset 0)