Files
shahrzadzandi09/app/Http/Controllers/FavoriteController.php
T

44 lines
1.2 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Tour;
use Illuminate\Http\Request;
class FavoriteController extends Controller
{
public function toggle(Request $request)
{
$type = $request->input('favoritable_type');
$id = $request->input('favoritable_id');
// چک کنید اگر null بود، متوقف شود
if (!$type || !$id) {
return back()->withErrors('اطلاعات ارسالی ناقص است!');
}
$user = auth()->user();
$exists = $user->favorites()
->where('favoritable_type', $type)
->where('favoritable_id', $id)
->first();
if ($exists) {
// اگر وجود داشت، حذفش کن
$exists->delete();
$message = 'از علاقه‌مندی‌ها حذف شد.';
} else {
// اگر وجود نداشت، یک رکورد جدید بساز
$user->favorites()->create([
'favoritable_type' => $type,
'favoritable_id' => $id,
]);
$message = 'به علاقه‌مندی‌ها اضافه شد.';
}
return back()->with('success', $message);
}
}