PaginatedResourceResponse.php 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Illuminate\Http\Resources\Json;
  3. use Illuminate\Support\Arr;
  4. class PaginatedResourceResponse extends ResourceResponse
  5. {
  6. /**
  7. * Create an HTTP response that represents the object.
  8. *
  9. * @param \Illuminate\Http\Request $request
  10. * @return \Illuminate\Http\JsonResponse
  11. */
  12. public function toResponse($request)
  13. {
  14. return tap(response()->json(
  15. $this->wrap(
  16. $this->resource->resolve($request),
  17. array_merge_recursive(
  18. $this->paginationInformation($request),
  19. $this->resource->with($request),
  20. $this->resource->additional
  21. )
  22. ),
  23. $this->calculateStatus()
  24. ), function ($response) use ($request) {
  25. $response->original = $this->resource->resource->pluck('resource');
  26. $this->resource->withResponse($request, $response);
  27. });
  28. }
  29. /**
  30. * Add the pagination information to the response.
  31. *
  32. * @param \Illuminate\Http\Request $request
  33. * @return array
  34. */
  35. protected function paginationInformation($request)
  36. {
  37. $paginated = $this->resource->resource->toArray();
  38. return [
  39. 'links' => $this->paginationLinks($paginated),
  40. 'meta' => $this->meta($paginated),
  41. ];
  42. }
  43. /**
  44. * Get the pagination links for the response.
  45. *
  46. * @param array $paginated
  47. * @return array
  48. */
  49. protected function paginationLinks($paginated)
  50. {
  51. return [
  52. 'first' => $paginated['first_page_url'] ?? null,
  53. 'last' => $paginated['last_page_url'] ?? null,
  54. 'prev' => $paginated['prev_page_url'] ?? null,
  55. 'next' => $paginated['next_page_url'] ?? null,
  56. ];
  57. }
  58. /**
  59. * Gather the meta data for the response.
  60. *
  61. * @param array $paginated
  62. * @return array
  63. */
  64. protected function meta($paginated)
  65. {
  66. return Arr::except($paginated, [
  67. 'data',
  68. 'first_page_url',
  69. 'last_page_url',
  70. 'prev_page_url',
  71. 'next_page_url',
  72. ]);
  73. }
  74. }