Я делаю API, используя Eloquent: Ресурсы API.
Это моя статья Ресурс:
class Article extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'slug' => $this->slug,
'name' => $this->name,
'comments' => $this->when($this->showComments(), function () {
$comments = config('eblogger.models.comment')::where([
'commentable_type' => get_class($this),
'commentable_id' => $this->id,
'parent_id' => 0,
])->orderBy('created_at', 'desc')->get();
$paginator = makePaginationCollection($comments, route('blog.comments'));
return CommentResource::collection($paginator);
}),
];
}
}
Это статья с комментариями. Я хочу получить нумерацию своих комментариев, поэтому я вызываю специального помощника
function makePaginationCollection($collection, $path)
{
$request = request();
$page = request('page', 1);
$perPage = config('settings.items_by_pages');
$paginate = new \Illuminate\Pagination\LengthAwarePaginator(
$collection->forPage($page, $perPage),
$collection->count(),
$perPage,
$page,
['path' => $path]
);
return $paginate;
}
Обновление: это моя коллекция ресурсов
class CommentCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'data' => $this->collection,
];
}
}
, но когда я проверяю ответ в devtools, я вижу
Я пытался с классом CommentCollection без успеха.
У вас есть идея?
Спасибо
Мое решение
наконец, благодаря @Rwd, я нашел это решение, но я думаю, что можно сделать лучше:
Это моя статья Ресурс:
public function toArray($request)
{
return [
// ...
'comments' => $this->when($this->showComments(), function() {
return new CommentCollection(
$this->comments()
->orderBy('created_at', 'desc')
->paginate(config('settings.items_by_pages'))
->withPath(route('blog.comments'))
);
})
];
}
А это моя коллекция ресурсов:
public function toArray($request)
{
return [
'data' => $this->collection,
'links' => $this->resource,
'meta' => $this->resource
];
}