where('user_id', Auth::id())->get()); $user = Auth::user(); $favorites = Favorite::with('favoritable') // لود پلیمورفیک ->where('user_id', $user->id) ->orderByDesc('id') ->paginate(9); return view('account.favorites', compact('favorites')); } /** * افزودن/حذف به صورت toggle (اگر موجود بود حذف کن، اگر نبود بساز). * این متد با پلیمورفیک بودن Favorite از هر دو مدل تور و پرواز پشتیبانی میکنه. */ public function toggle(Request $request) { // چک اینکه کاربر ورود شدهست if (!Auth::check()) { return back()->with('error', 'برای افزودن به علاقهمندی باید ورود شوی'); } $data = $request->validate([ 'favoritable_type' => 'required|string', 'favoritable_id' => 'required|integer', ]); $type = $data['favoritable_type']; $id = $data['favoritable_id']; // بررسی اینکه مدل درخواستی واقعاً وجود داره (مثلاً Tour یا Flight) if (!class_exists($type)) { return back()->with('error', 'مدل معتبر نیست'); } $model = $type::find($id); if (!$model) { return back()->with('error', 'مورد یافت نشد'); } // یافتن علاقهمندی موجود $favorite = Favorite::where('user_id', Auth::id()) ->where('favoritable_type', $type) ->where('favoritable_id', $id) ->first(); if ($favorite) { $favorite->delete(); // حذف از علاقهمندیها $message = 'از علاقهمندیها حذف شد'; } else { Favorite::create([ 'user_id' => Auth::id(), 'favoritable_type' => $type, 'favoritable_id' => $id, ]); $message = 'به علاقهمندیها افزوده شد'; } return back()->with('success', $message); } }