AttachmentResource.php 884 B

123456789101112131415161718192021222324252627282930313233
  1. <?php
  2. namespace App\Http\Resources;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Http\Resources\Json\JsonResource;
  5. class AttachmentResource extends JsonResource
  6. {
  7. public function toArray(Request $request): array
  8. {
  9. return [
  10. 'id' => $this->id,
  11. 'filename' => $this->filename,
  12. 'filepath' => $this->filepath,
  13. 'mime_type' => $this->mime_type,
  14. 'size' => $this->size,
  15. 'size_human' => $this->formatBytes($this->size),
  16. 'created_at' => $this->created_at->toISOString(),
  17. ];
  18. }
  19. private function formatBytes($bytes, $precision = 2)
  20. {
  21. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  22. for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
  23. $bytes /= 1024;
  24. }
  25. return round($bytes, $precision) . ' ' . $units[$i];
  26. }
  27. }