UserResource.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. use Illuminate\Support\Facades\Storage;
  8. class UserResource extends JsonResource
  9. {
  10. public function toArray(Request $request): array
  11. {
  12. return [
  13. 'id' => $this->id,
  14. 'name' => $this->name,
  15. 'cpf' => $this->cpf,
  16. 'phone' => $this->phone,
  17. 'email' => $this->email,
  18. 'language' => $this->language,
  19. 'user_type' => $this->user_type,
  20. 'user_type_label' => $this->whenLoaded('userType', fn() => $this->userType?->label),
  21. 'status' => $this->status,
  22. 'state_id' => $this->state_id,
  23. 'unit_id' => $this->whenLoaded('units', fn() => $this->units->first()?->id),
  24. 'units' => $this->whenLoaded('units', fn() => $this->units->map(fn($u) => [
  25. 'id' => $u->id,
  26. 'fantasy_name' => $u->fantasy_name,
  27. ])->values()->toArray()),
  28. 'avatar_url' => $this->avatar_url
  29. ? Storage::temporaryUrl($this->avatar_url, now()->addHours(24))
  30. : null,
  31. 'last_login_at' => $this->last_login_at
  32. ? Carbon::parse($this->last_login_at)->format('Y-m-d H:i:s')
  33. : null,
  34. 'created_at' => Carbon::parse($this->created_at)->format('Y-m-d'),
  35. 'updated_at' => Carbon::parse($this->updated_at)->format('Y-m-d'),
  36. 'state' => $this->whenLoaded('state', fn() => [
  37. 'id' => $this->state->id,
  38. 'name' => $this->state->name,
  39. 'code' => $this->state->code,
  40. ]),
  41. ];
  42. }
  43. public static function collection($resource): AnonymousResourceCollection
  44. {
  45. return parent::collection($resource);
  46. }
  47. }