ServicePackageResource.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace App\Http\Resources;
  3. use App\Models\ServicePackage;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Http\Resources\Json\JsonResource;
  6. use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
  7. class ServicePackageResource extends JsonResource
  8. {
  9. /**
  10. * Transform the resource into an array.
  11. *
  12. * @return array<string, mixed>
  13. */
  14. public function toArray(Request $request): array
  15. {
  16. return [
  17. 'id' => $this->id,
  18. 'client_id' => $this->client_id,
  19. 'provider_id' => $this->provider_id,
  20. 'status' => $this->status?->value,
  21. 'schedule_ids' => $this->whenLoaded('items', fn () => $this->items->pluck('schedule_id')->values()),
  22. 'items' => $this->whenLoaded('items', fn () => ServicePackageItemResource::collection($this->items)),
  23. 'schedules' => $this->whenLoaded('items', fn () => ScheduleResource::collection(
  24. $this->items->pluck('schedule')->filter()->values(),
  25. )),
  26. 'total_amount' => $this->whenLoaded('items', fn () =>
  27. (float) $this->items->sum(fn($item) => (float) ($item->schedule?->total_amount ?? 0))
  28. ),
  29. 'created_at' => $this->created_at?->toISOString(),
  30. 'updated_at' => $this->updated_at?->toISOString(),
  31. ];
  32. }
  33. /**
  34. * @param \Illuminate\Database\Eloquent\Collection<ServicePackage> $resource
  35. * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection<ServicePackageResource>
  36. */
  37. public static function collection($resource): AnonymousResourceCollection
  38. {
  39. return parent::collection($resource);
  40. }
  41. }