feat: add user favorites management
This commit is contained in:
@@ -0,0 +1,76 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Account;
|
||||||
|
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Models\Favorite;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
|
||||||
|
class FavoriteController extends Controller
|
||||||
|
{
|
||||||
|
public function index()
|
||||||
|
{
|
||||||
|
// dd(Auth::id(), Favorite::with('favoritable')->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);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user