Mohsen's avatar

Laravel lazy eager loading with pagination

Hi I have two models , Tag and Post and many to many relation between them . I want to show and also paginate posts with specific tag . what is the best practice for this situation . I used the function but not work :

        public function getPosts($tagId,$rowsCount)
    {
                return App\Models\Tag::where('id',$tagId)->with(['posts' => function($q) use ($rowsCount){
                  $q->paginate($rowsCount);
                 }])->get();
     }
0 likes
2 replies
willvincent's avatar
Level 54

Try this instead:

public function getPosts($tagId, $rowsCount) {
  return Post::whereHas('tags', function ($q) use ($tagId) {
             $q->where('id', $tagId);
           })
           ->with('tags')
           ->paginate($rowsCount);
}
1 like
Mohsen's avatar

thank you very much for your help ....

Please or to participate in this conversation.