laravelpaginationlaravel-collectionlaravel-resource

paginate relational resource in laravel api


I have two models, User and Comment, Each User can have multiple Comment, I can call paginate(3) on User and get 3 User in output per page but I need same thing as User for comments in UserCollection. Is it possible to limit comments that comes by UserCollection by paginating them too?


Solution

  • Yes you can, you just have to add in the third parameter of pageName to the paginate method to differentiate between them.

    Something like:

    $users->paginate($perPage, ['*'], 'users')
    $comments->paginate($perPage, ['*'], 'comments_'. $user_id)
    

    https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Builder.html#method_paginate

    Note: While you can do this, I personally would just fetch the first 3/5 comments and then have a button saying click to load more and then have a separate route that you call via an AJAX request to get them.