GroupService.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Group;
  4. use Illuminate\Database\Eloquent\Collection;
  5. class GroupService
  6. {
  7. public function getAll(): Collection
  8. {
  9. return Group::with('units')
  10. ->orderBy('name')
  11. ->get();
  12. }
  13. public function findById(int $id): ?Group
  14. {
  15. return Group::with('units')->find($id);
  16. }
  17. public function create(array $data): Group
  18. {
  19. $group = Group::create([
  20. 'name' => $data['name'],
  21. 'status' => $data['status'] ?? 'ACTIVE',
  22. ]);
  23. if (!empty($data['unit_ids'])) {
  24. $group->units()->sync($data['unit_ids']);
  25. }
  26. return $group->load('units');
  27. }
  28. public function update(int $id, array $data): ?Group
  29. {
  30. $group = $this->findById($id);
  31. if (!$group) {
  32. return null;
  33. }
  34. $group->update(array_filter([
  35. 'name' => $data['name'] ?? null,
  36. 'status' => $data['status'] ?? null,
  37. ], fn($v) => $v !== null));
  38. if (array_key_exists('unit_ids', $data)) {
  39. $group->units()->sync($data['unit_ids'] ?? []);
  40. }
  41. return $group->fresh('units');
  42. }
  43. public function delete(int $id): bool
  44. {
  45. $group = $this->findById($id);
  46. if (!$group) {
  47. return false;
  48. }
  49. $group->units()->detach();
  50. return $group->delete();
  51. }
  52. }