4

I'm having issues with pagination after I use a resource to display data. Before this, I was using this code to display data, and the output shows the pagination as well.

Output enter image description here

Controller

$All = Customers::with('order')->paginate(10);

return response()->json([
    'code' => 0,
    'success' => true,
    'data' => $All,
], 200);

But right after I'm using Resources to display data, the pagination is gone.

$All = Customers::with('order')->paginate(10);

return response()->json([
    'code' => 0,
    'success' => true,
    'data' => DataResource::collection($All),
], 200);

DataResource

public function toArray($request)
{
    //return parent::toArray($request);
    return [
        'name' => $this->name,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'order' => Resources::collection($this->order)
    ];
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Choy
  • 452
  • 1
  • 5
  • 19

1 Answers1

0

It appears you are using Eloquent: API Resources, although it is uncertain which version of Laravel is used because the newer version shows a very different pagination.

When I show a dump() of the first snippet, the paginator (also called the LengthAwarePaginator object) is in the root of the response:

LengthAwarePaginator {#406 ▼
  #total: 3
  #lastPage: 1
  #items: Collection {#401 ▶}
  #perPage: 10
  #currentPage: 1
  #path: "http://laravelsoplayground"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}

After the resources have been applied, the paginator is still present but has been moved to the resource attribute.

AnonymousResourceCollection {#331 ▼
  +collects: "App\Http\Resources\DataResource"
  +collection: Collection {#214 ▶}
  +resource: LengthAwarePaginator {#406 ▶}
  +with: []
  +additional: []
}
JorisJ1
  • 922
  • 2
  • 12
  • 22