GroupResource.php 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. <?php
  2. namespace App\Http\Resources;
  3. use Carbon\Carbon;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
  6. use Illuminate\Http\Resources\Json\JsonResource;
  7. class GroupResource extends JsonResource
  8. {
  9. public function toArray(Request $request): array
  10. {
  11. return [
  12. 'id' => $this->id,
  13. 'name' => $this->name,
  14. 'status' => $this->status,
  15. 'active_units' => $this->whenLoaded('units', fn() => $this->units->count()),
  16. 'unit_ids' => $this->whenLoaded('units', fn() => $this->units->pluck('id')),
  17. 'units' => $this->whenLoaded('units', fn() => $this->units->map(fn($unit) => [
  18. 'id' => $unit->id,
  19. 'fantasy_name' => $unit->fantasy_name,
  20. ])),
  21. 'created_at' => Carbon::parse($this->created_at)->format('Y-m-d'),
  22. 'updated_at' => Carbon::parse($this->updated_at)->format('Y-m-d'),
  23. ];
  24. }
  25. public static function collection($resource): AnonymousResourceCollection
  26. {
  27. return parent::collection($resource);
  28. }
  29. }