StoreItemService.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Services;
  3. use App\Models\StoreItem;
  4. use App\Models\StoreItemInterest;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Illuminate\Support\Facades\Auth;
  7. use Illuminate\Support\Facades\DB;
  8. class StoreItemService
  9. {
  10. public function getAll(): Collection
  11. {
  12. return StoreItem::with('category')->orderBy('name')->get();
  13. }
  14. public function findById(int $id): ?StoreItem
  15. {
  16. return StoreItem::with(['category', 'media'])->find($id);
  17. }
  18. public function create(array $data): StoreItem
  19. {
  20. return StoreItem::create($data);
  21. }
  22. public function update(int $id, array $data): ?StoreItem
  23. {
  24. $model = StoreItem::find($id);
  25. if (!$model) {
  26. return null;
  27. }
  28. $model->update($data);
  29. return $model->fresh(['category']);
  30. }
  31. public function delete(int $id): bool
  32. {
  33. $model = StoreItem::find($id);
  34. if (!$model) {
  35. return false;
  36. }
  37. return $model->delete();
  38. }
  39. public function getMyInterests(): Collection
  40. {
  41. $userId = Auth::id();
  42. return StoreItem::with('category')
  43. ->whereHas('interests', fn($q) => $q->where('user_id', $userId))
  44. ->orderBy('name')
  45. ->get();
  46. }
  47. public function toggleInterest(int $storeItemId): array
  48. {
  49. $userId = Auth::id();
  50. $existing = StoreItemInterest::where('user_id', $userId)
  51. ->where('store_item_id', $storeItemId)
  52. ->first();
  53. if ($existing) {
  54. $existing->delete();
  55. return ['interested' => false];
  56. }
  57. StoreItemInterest::create(['user_id' => $userId, 'store_item_id' => $storeItemId]);
  58. return ['interested' => true];
  59. }
  60. }