73 lines
2.0 KiB
PHP
73 lines
2.0 KiB
PHP
<?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'));
|
|
}
|
|
|
|
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'];
|
|
|
|
|
|
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);
|
|
}
|
|
}
|