ResourceCollection.php 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Illuminate\Http\Resources\Json;
  3. use IteratorAggregate;
  4. use Illuminate\Pagination\AbstractPaginator;
  5. use Illuminate\Http\Resources\CollectsResources;
  6. class ResourceCollection extends JsonResource implements IteratorAggregate
  7. {
  8. use CollectsResources;
  9. /**
  10. * The resource that this resource collects.
  11. *
  12. * @var string
  13. */
  14. public $collects;
  15. /**
  16. * The mapped collection instance.
  17. *
  18. * @var \Illuminate\Support\Collection
  19. */
  20. public $collection;
  21. /**
  22. * Create a new resource instance.
  23. *
  24. * @param mixed $resource
  25. * @return void
  26. */
  27. public function __construct($resource)
  28. {
  29. parent::__construct($resource);
  30. $this->resource = $this->collectResource($resource);
  31. }
  32. /**
  33. * Transform the resource into a JSON array.
  34. *
  35. * @param \Illuminate\Http\Request $request
  36. * @return array
  37. */
  38. public function toArray($request)
  39. {
  40. return $this->collection->map->toArray($request)->all();
  41. }
  42. /**
  43. * Create an HTTP response that represents the object.
  44. *
  45. * @param \Illuminate\Http\Request $request
  46. * @return \Illuminate\Http\JsonResponse
  47. */
  48. public function toResponse($request)
  49. {
  50. return $this->resource instanceof AbstractPaginator
  51. ? (new PaginatedResourceResponse($this))->toResponse($request)
  52. : parent::toResponse($request);
  53. }
  54. }