amitsolanki24_'s avatar

Relationship pagination

Hello everyone, I hope all are doing good.

Here is my problem, How can I add pagination in laravel hasmany relationship?

Hashtag::withCount(['posts as count' => function($query) {
   $query->active()
     ->whereHas('user', function ($subQuery) {
         $subQuery->active();
     });
   }
 ])
 ->with([
   'posts' => function ($query) {
      $query->active() 
         ->withWhereHas('user', function ($subQuery) {
           $subQuery->active();
         })
         ->withCount([
          'likes as total_likes',
          'comments as total_comments'
         ])
         ->orderByRaw('total_likes + total_comments DESC')
        ->paginate(5);
     }
 }]
 ->latest('count')
 ->paginate(10);

When I use paginate() or take(), limit() in with() then it will return incorrect records but when I remove paginate(), take() or limit() it will give all the posts of a hashtags.

0 likes
9 replies
jlrdw's avatar

Start troubleshooting by using toSql().

To be honest i've never seen anything quite like that with paginate twice.

I use double pagination sometimes but each paginator has its own name.

2 likes
gych's avatar

What you're trying to do by using pagination on a relation that you're eager loading isn't possible in Laravel. Laravel's eager loading (with) is not designed to handle pagination within related models.

You could first paginate the Hashtag model, and then separately fetch and paginate the posts for each Hashtag.

1 like
jaseofspades88's avatar

This doesn't make sense. Returning two paginated datasets is something you never see people doing and for a good reason. Have two separate pagination instances and name them differently.

2 likes
amitsolanki24_'s avatar

@jaseofspades88 yeah, I haven't fixed this code because it is not giving me correct data.

I'll change pagination key for both (page and subpage).

Please or to participate in this conversation.