CategoryService.php 986 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Category;
  4. use Illuminate\Database\Eloquent\Collection;
  5. class CategoryService
  6. {
  7. public function getAll(?string $type = null): Collection
  8. {
  9. return Category::where('active', true)
  10. ->when($type, fn($q) => $q->where('type', $type))
  11. ->orderBy('name')
  12. ->get();
  13. }
  14. public function findById(int $id): ?Category
  15. {
  16. return Category::find($id);
  17. }
  18. public function create(array $data): Category
  19. {
  20. return Category::create($data);
  21. }
  22. public function update(int $id, array $data): ?Category
  23. {
  24. $model = $this->findById($id);
  25. if (!$model) {
  26. return null;
  27. }
  28. $model->update($data);
  29. return $model->fresh();
  30. }
  31. public function delete(int $id): bool
  32. {
  33. $model = $this->findById($id);
  34. if (!$model) {
  35. return false;
  36. }
  37. return $model->delete();
  38. }
  39. }