107 lines
3.3 KiB
PHP
107 lines
3.3 KiB
PHP
<?php
|
||
|
||
namespace App\Http\Controllers\Shop;
|
||
|
||
use App\Http\Controllers\Controller;
|
||
use App\Models\Product;
|
||
use Illuminate\Http\Request;
|
||
|
||
class CartController extends Controller
|
||
{
|
||
public function index()
|
||
{
|
||
$cart = (array) session()->get('cart', []);
|
||
$products = Product::query()
|
||
->whereIn('id', array_keys($cart))
|
||
->where('is_active', true)
|
||
->with('category')
|
||
->get()
|
||
->keyBy('id');
|
||
|
||
$items = collect($cart)
|
||
->map(function ($quantity, $productId) use ($products) {
|
||
$product = $products->get((int) $productId);
|
||
if (!$product) {
|
||
return null;
|
||
}
|
||
|
||
$qty = max(1, (int) $quantity);
|
||
|
||
return [
|
||
'product' => $product,
|
||
'quantity' => $qty,
|
||
'subtotal' => (float) $product->price * $qty,
|
||
];
|
||
})
|
||
->filter()
|
||
->values();
|
||
|
||
return view('shop.cart', [
|
||
'items' => $items,
|
||
'itemsCount' => $items->sum('quantity'),
|
||
'total' => $items->sum('subtotal'),
|
||
]);
|
||
}
|
||
|
||
public function add(Product $product)
|
||
{
|
||
if (!$product->is_active || $product->stock < 1) {
|
||
return back()->with('status', 'Товар сейчас недоступен для заказа.');
|
||
}
|
||
|
||
$cart = (array) session()->get('cart', []);
|
||
$current = (int) ($cart[$product->id] ?? 0);
|
||
|
||
if ($current >= $product->stock) {
|
||
return back()->with('status', 'В корзине уже максимальное доступное количество.');
|
||
}
|
||
|
||
$cart[$product->id] = $current + 1;
|
||
session()->put('cart', $cart);
|
||
|
||
return back()->with('status', "Товар \"{$product->name}\" добавлен в корзину.");
|
||
}
|
||
|
||
public function update(Request $request, Product $product)
|
||
{
|
||
$validated = $request->validate([
|
||
'quantity' => ['required', 'integer', 'min:1', 'max:99'],
|
||
]);
|
||
|
||
$cart = (array) session()->get('cart', []);
|
||
if (!isset($cart[$product->id])) {
|
||
return back();
|
||
}
|
||
|
||
$available = max(0, (int) $product->stock);
|
||
$quantity = min((int) $validated['quantity'], $available);
|
||
|
||
if ($quantity < 1) {
|
||
unset($cart[$product->id]);
|
||
session()->put('cart', $cart);
|
||
|
||
return back()->with('status', "Товар \"{$product->name}\" удален из корзины.");
|
||
}
|
||
|
||
$cart[$product->id] = $quantity;
|
||
session()->put('cart', $cart);
|
||
|
||
$message = $quantity < (int) $validated['quantity']
|
||
? 'Количество ограничено текущим остатком.'
|
||
: 'Количество товара обновлено.';
|
||
|
||
return back()->with('status', $message);
|
||
}
|
||
|
||
public function remove(Product $product)
|
||
{
|
||
$cart = (array) session()->get('cart', []);
|
||
if (isset($cart[$product->id])) {
|
||
unset($cart[$product->id]);
|
||
session()->put('cart', $cart);
|
||
}
|
||
|
||
return back()->with('status', "Товар \"{$product->name}\" удален из корзины.");
|
||
}
|
||
}
|