I have a posts table and comments table, comment belongs to post, and I have the relationship setup in Post and Comment model. I did sort posts by the number of comments of each post like this:
$posts = Post::with('comments')->get()->sortBy(function($post) {
return $post->comments->count();
});
What I wonder is how I can paginate these sorted posts?
$posts = Post::with('comments')->get()->sortBy(function($post) {
return $post->comments->count();
})->paginate(20);
doesn't work and gives me error that says paginate is an undefined method.
Just remove the
get()
in the chained calls and see what you get, paginate should replace get() call.This sounds obvious, but Eloquent will not return a result set here, but rather it will return a collection.
If you dig into the source (
Builder::get
callsBuilder::getFresh
, which callsBuilder::runSelect
, which callsConnection::select
), you'll find that it's intention is to simply return the results, which are then placed into a collection (which has the sortBy method).If you want to have pagination without loading every item, then you need to use @Marcin's solution (duplicated below):
I don't know if you can do it using Eloquent but you can use join for this:
However it seems that in this case all records are taken from database and displayed only those from paginator, so if you have many records it's waste of resources. It seems you should do manual pagination for this:
using
skip
andtake
but I'm not Eloquent expert and maybe there's a better solution to achieve your goal so you can wait and maybe someone will give a better answer.