user16390519
user16390519

Reputation:

Laravel pagination Relation with API resources

I have user resource as follow:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'posts' => PostResource::collection($this->posts()->paginate(10)),
    ];
}   

In User model, there is hasMany relation posts

My problem with paginating, the links and meta of post paginate does not show just get 10 posts without links of paginate

My controller

$user = User::query()
    ->where('id', $userId)
    ->with('posts')
    ->firstOrFail();

return new UserResource($user);

Upvotes: 0

Views: 578

Answers (2)

Ardi Tan
Ardi Tan

Reputation: 142

I think it's because you return the posts attribute as a collection not pagination.

Try

return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'posts' => $this->posts()->paginate(10),
    ];

Upvotes: 1

Fabio Carpinato
Fabio Carpinato

Reputation: 1181

Laravel doesn't handle this case for you.

You have just 2 options:

  1. Write a custom pagination logic
  2. Just use two different API's with dedicated pagination in the posts API (recommended)

Upvotes: 0

Related Questions