panthro's avatar

Paginating A Relationship

I need to paginate a relationship. Therefore, it is my understanding that I cannot use with. Therefore I do something like this:

$post = Post::where('slug', $slug)->firstOrFail();
$post->comments()->cursorPaginate(10);

I have a post API resource too which organises the comments relationship:

public function toArray(Request $request): array
    {
        return [
            other post fields....
             'comments' => CommentResource::collection($this->whenLoaded('comments')),

However, I am no longer loading the comments relationship using with, and when i dd the comments appear under attributes and not relationships is there a way to assign comments to be under relationships but maintain pagination?

In doing so, the API resource should then work.

0 likes
2 replies
Snapey's avatar

include comments as a separarate collection in the response?

Laravel 11 can now eager load relations with a limit.

2 likes

Please or to participate in this conversation.