Repository navigation
JSON:API included relationship pagination #59225
|
I don't know if this is possible, but it is allowed as per the JSON:API spec1 and would help with server loads. I tried to get it to work with Laravel 13 version, but couldn't figure out how to do it, if it is even possible. <?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\JsonApi\JsonApiResource;
class PostResource extends JsonApiResource
{
public function toAttributes(Request $request): array
{
return [
'title' => $this->title,
'slug' => $this->slug,
'body' => $this->body,
'published_at' => $this->published_at,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
public function toRelationships(Request $request): array
{
return [
'blog' => BlogResource::class,
'author' => UserResource::class,
// These should be paginated when included to avoid returning too much data
'comments' => CommentResource::class,
'tags' => TagResource::class,
];
}
}Footnotes
|
Replies: 4 comments 5 replies
|
Hi. How would you go to page 2 of comments? Requesting same resource again would be a trafic waste. I think that page 2 of comments should be retrieved from a different route:
and to flag this in the initial response a bool flag could be returned: has_more_comments:true Or This would mean retrieving n+1 comments, returning n of then and using the extra comment for the flag. Eager loading comments on a list of posts would be affected by this, or maybe even blocked. |
|
To prevent this, you could fetch first the resoure with the one to many relation count and fetch the many relations via a second call. |
|
https://github.com/staudenmeir/eloquent-eager-limit this can be used for paginated eagerloading. It is included in laravel since v 11. It support offset and limit. |
|
yes it s possible; I had the same problem (on my e-commerce site)—the solution is simple public function toRelationships(Request $request): array
{
return [
'blog' => BlogResource::class,
'author' => UserResource::class,
'comments' => fn() =>
CommentResource::collection(
$this->whenLoaded('comments', fn() =>
$this->comments()->paginate(10)
)
),
'tags' => TagResource::class,
];
}
/*it also reduces server load*/ |
yes it s possible; I had the same problem (on my e-commerce site)—the solution is simple
toRelationships()try something like this in the method: