| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <?php
- namespace App\Services;
- use App\Models\StoreItem;
- use App\Models\StoreItemInterest;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\DB;
- class StoreItemService
- {
- public function getAll(): Collection
- {
- return StoreItem::with('category')->orderBy('name')->get();
- }
- public function findById(int $id): ?StoreItem
- {
- return StoreItem::with(['category', 'media'])->find($id);
- }
- public function create(array $data): StoreItem
- {
- return StoreItem::create($data);
- }
- public function update(int $id, array $data): ?StoreItem
- {
- $model = StoreItem::find($id);
- if (!$model) {
- return null;
- }
- $model->update($data);
- return $model->fresh(['category']);
- }
- public function delete(int $id): bool
- {
- $model = StoreItem::find($id);
- if (!$model) {
- return false;
- }
- return $model->delete();
- }
- public function getMyInterests(): Collection
- {
- $userId = Auth::id();
- return StoreItem::with('category')
- ->whereHas('interests', fn($q) => $q->where('user_id', $userId))
- ->orderBy('name')
- ->get();
- }
- public function toggleInterest(int $storeItemId): array
- {
- $userId = Auth::id();
- $existing = StoreItemInterest::where('user_id', $userId)
- ->where('store_item_id', $storeItemId)
- ->first();
- if ($existing) {
- $existing->delete();
- return ['interested' => false];
- }
- StoreItemInterest::create(['user_id' => $userId, 'store_item_id' => $storeItemId]);
- return ['interested' => true];
- }
- }
|