PetroGromovo's avatar

How to data returned from Repository with pagination apply Resource?

On Laravel 10 site I use Repository working with db and in controller I need to return data with Resource

/app/Http/Controllers/Api/ItemController.php :

<?php
class ItemController extends Controller
{
    public function index()
    {
        $request = request();
        $data = $itemRepository->index(
            page: $request->page ?? 1,
            filters: $request->only('search'),
        );
        return ItemResource::collection($data);
    }

In ItemRepository class pagination is returned:

public function index(int $page = 1, array $filters = []): array
{
    $paginationPerPage = 10;
    $items = Item::paginate($paginationPerPage, array('*'), 'page', 1);
    ...
    return [
        'items' => $items,
        'paginationPerPage' => $paginationPerPage,
    ];
}

But I got error :

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id

when in ItemResource I try to use

class ItemResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,

returns type LengthAwarePaginator and it has items protected property, so I have no access to it?

I need pagination object used here and do not know how that can be salved ?

0 likes
1 reply
shariff's avatar
shariff
Best Answer
Level 51

Did you try like this? return ItemResource::collection($data['items']); And I didn't understood what is use of returning $paginationPerPage ?

1 like

Please or to participate in this conversation.