UserService.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\UserTypeEnum;
  4. use App\Models\User;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Illuminate\Support\Facades\Auth;
  7. class UserService
  8. {
  9. public function authUser(): ?User
  10. {
  11. $user = Auth::user();
  12. return $user;
  13. }
  14. public function getAll(): Collection
  15. {
  16. return User::with(['position', 'sector'])->orderBy("created_at", "desc")->get();
  17. }
  18. public function getAllPaginated(array $filters = [], int $perPage = 10): \Illuminate\Pagination\LengthAwarePaginator
  19. {
  20. $query = User::with(['position', 'sector'])->orderBy('created_at', 'desc');
  21. if (!empty($filters['type'])) {
  22. $query->where('type', $filters['type']);
  23. }
  24. if (!empty($filters['status'])) {
  25. $query->where('status', $filters['status']);
  26. }
  27. if (!empty($filters['search'])) {
  28. $search = $filters['search'];
  29. $query->where(function ($q) use ($search) {
  30. $q->where('name', 'like', "%{$search}%")
  31. ->orWhere('email', 'like', "%{$search}%")
  32. ->orWhere('cpf', 'like', "%{$search}%")
  33. ->orWhere('registration', 'like', "%{$search}%");
  34. });
  35. }
  36. return $query->paginate($perPage);
  37. }
  38. public function findById(int $id): ?User
  39. {
  40. return User::find($id);
  41. }
  42. public function create(array $data): User
  43. {
  44. return User::create($data);
  45. }
  46. public function update(int $id, array $data): ?User
  47. {
  48. $model = $this->findById($id);
  49. if (!$model) {
  50. return null;
  51. }
  52. $model->update($data);
  53. return $model->fresh();
  54. }
  55. public function delete(int $id): bool
  56. {
  57. $model = $this->findById($id);
  58. if (!$model) {
  59. return false;
  60. }
  61. return $model->delete();
  62. }
  63. public function getUserTypes(): array
  64. {
  65. return UserTypeEnum::toArray();
  66. }
  67. }