| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- <?php
- namespace App\Services;
- use App\Models\Group;
- use Illuminate\Database\Eloquent\Collection;
- class GroupService
- {
- public function getAll(): Collection
- {
- return Group::with('units')
- ->orderBy('name')
- ->get();
- }
- public function findById(int $id): ?Group
- {
- return Group::with('units')->find($id);
- }
- public function create(array $data): Group
- {
- $group = Group::create([
- 'name' => $data['name'],
- 'status' => $data['status'] ?? 'ACTIVE',
- ]);
- if (!empty($data['unit_ids'])) {
- $group->units()->sync($data['unit_ids']);
- }
- return $group->load('units');
- }
- public function update(int $id, array $data): ?Group
- {
- $group = $this->findById($id);
- if (!$group) {
- return null;
- }
- $group->update(array_filter([
- 'name' => $data['name'] ?? null,
- 'status' => $data['status'] ?? null,
- ], fn($v) => $v !== null));
- if (array_key_exists('unit_ids', $data)) {
- $group->units()->sync($data['unit_ids'] ?? []);
- }
- return $group->fresh('units');
- }
- public function delete(int $id): bool
- {
- $group = $this->findById($id);
- if (!$group) {
- return false;
- }
- $group->units()->detach();
- return $group->delete();
- }
- }
|