This commit is contained in:
50
app/Http/Controllers/Shop/FavoriteController.php
Normal file
50
app/Http/Controllers/Shop/FavoriteController.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Shop;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Product;
|
||||
|
||||
class FavoriteController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$favoriteIds = $this->favoriteIds();
|
||||
$position = array_flip($favoriteIds);
|
||||
|
||||
$products = Product::query()
|
||||
->whereIn('id', $favoriteIds)
|
||||
->where('is_active', true)
|
||||
->with('category')
|
||||
->get()
|
||||
->sortBy(fn (Product $product) => $position[$product->id] ?? PHP_INT_MAX)
|
||||
->values();
|
||||
|
||||
return view('shop.favorites', [
|
||||
'products' => $products,
|
||||
]);
|
||||
}
|
||||
|
||||
public function toggle(Product $product)
|
||||
{
|
||||
$favorites = $this->favoriteIds();
|
||||
$exists = in_array($product->id, $favorites, true);
|
||||
|
||||
if ($exists) {
|
||||
$favorites = array_values(array_filter($favorites, fn (int $id) => $id !== $product->id));
|
||||
session()->put('favorites', $favorites);
|
||||
|
||||
return back()->with('status', "Товар \"{$product->name}\" удален из избранного.");
|
||||
}
|
||||
|
||||
$favorites[] = $product->id;
|
||||
session()->put('favorites', array_values(array_unique($favorites)));
|
||||
|
||||
return back()->with('status', "Товар \"{$product->name}\" добавлен в избранное.");
|
||||
}
|
||||
|
||||
private function favoriteIds(): array
|
||||
{
|
||||
return array_values(array_map('intval', (array) session()->get('favorites', [])));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user